Simple Odata Client - How to add oAuth Token in each request header?

霸气de小男生 提交于 2019-12-04 20:33:30

Apparently I should provide an explanation of why this is the answer.

Explanation: this is how you add the token for Simple ODataClient.

var settings = new ODataClientSettings(new Uri("http://localhost:9000/"));
settings.BeforeRequest += delegate(HttpRequestMessage message)
{
    message.Headers.Add("Authorization", "Bearer " + token.AccessToken);
};

var client = new ODataClient(settings);

Instead of using the delegate method to intercept and add the Authorization header on every Http call, a clearer/cleaner solution is to instantiate the ODataClient with an existing HttpClient instance.

This also allows you to control the HttpClient lifecycle externally.

The code below is an extract of a .Net core app using an Azure AD OAuth2 token to connect to a Dynamics 365 OData Web API.

        httpClient.BaseAddress = new Uri(yourODataServiceRootURL);
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", yourBearerAccessToken);

        //Use the httpClient we setup with the Bearer token header
        var odataSettings = new ODataClientSettings(httpClient, new Uri("api/data/v9.1", UriKind.Relative));

        var odataClient = new ODataClient(odataSettings);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!