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

Rahul picture Rahul · Jan 26, 2017 · Viewed 9.2k times · Source

In Microsoft oData v4 proxy client, there is an option to add auth token into each request. It can be achieved by following way:

var container = new Default.Container(new Uri(http://localhost:9000/));

//Registering the handle to the BuildingRequest event. 
container.BuildingRequest += (sender, e) => OnBuildingRequest(sender, e, accessToken);


//Every time a OData request is build it adds an Authorization Header with the acesstoken 
private static void OnBuildingRequest(object sender, BuildingRequestEventArgs e, TokenResponse token)
{
 e.Headers.Add("Authorization", "Bearer " + token.AccessToken);
}

How can I do the same using simple odata client?

Answer

Paul - Soura Tech LLC picture Paul - Soura Tech LLC · Apr 27, 2017

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);