'Setting headers for Odata client
I've been trying to set authorization header value for Odata
client. After I instantiate the client, I do it like this:
container.BuildingRequest += (sender, e) => OnBuildingRequest(sender, e, accessToken);
private static void OnBuildingRequest(object sender, BuildingRequestEventArgs e, string token)
{
e.Headers.Add("Authorization", "Bearer " + token);
}
When debugging, it shows that the event handler gets triggered AFTER the request to the WEB API is made, which is really strange for me. The documentation says:
"This event is fired before a request message object is built"
What seems to be the problem here?
Solution 1:[1]
After lots of research, I found the cause of the problem: the event handler "BuildingRequest" doesn't gets triggered until you make an actual request, that is if you have a method something like:
public IQueryable<Package> GetPackages()
{
return _container.Packages.AsQueryable();
}
"BuildingRequest" handler will not be triggered. You must execute it, that is do something like:
_container.Packages.ToList();
In order for it to work.
Solution 2:[2]
You have to set it like this:
container.SendingRequest2 += new EventHandler<SendingRequest2EventArgs>(delegate (object sender, SendingRequest2EventArgs e)
{
e.RequestMessage.SetHeader("Authorization", "Bearer " + token);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | MichealOchajo |
Solution 2 |