Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add a custom authorization header to a Windows Store App OData client?

I'm building a Windows Store App using the Windows Runtime. I'm accessing an OData service that uses Basic authentication. I'm using the WCF Data Services Tools for Windows Store Apps library (Microsoft.Data.Services.Client.WindowsStore).

The authentication string is a custom format, so I can't just use a NetworkCredential(username, password). I need to add the header myself to every request from my DataServiceContext.

I tried using the following code:

proxy.SendingRequest += (s, e) =>
{
   e.RequestHeaders.Add("Authorization", authHeader);
}

But I receive the error:

'System.Net.WebHeaderCollection' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'System.Net.WebHeaderCollection' could be found
like image 229
Grant Holliday Avatar asked Dec 22 '12 10:12

Grant Holliday


1 Answers

You can use the new SendingRequest2 event that fires after the request is built and before it is sent to the server.

There is a RequestMessage.SetHeader(headername, value) method that you can use to set headers. Set the value to null to remove a header.

proxy.SendingRequest2 += (sender, eventArgs) =>
{
    eventArgs.RequestMessage.SetHeader("Authorization", authHeader);
};

The WCF Data Services team blog talks more about it:

SendingRequest2 (and its deprecated predecessor SendingRequest) fires after the request is built. WebRequest does not allow you to modify the URL after construction. The new event lets you modify the URL before we build the underlying request, giving you full control over the request.

like image 75
Grant Holliday Avatar answered Sep 29 '22 23:09

Grant Holliday