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

1

6

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
Illuminance answered 22/12, 2012 at 10:3 Comment(0)
I
16

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.

Illuminance answered 22/12, 2012 at 10:3 Comment(3)
you asked and answered your own question in a short time. what's the point?Antilogism
@Antilogism to make the internet better blog.stackoverflow.com/2011/07/…Illuminance
Helped me. Thanks.Duax

© 2022 - 2024 — McMap. All rights reserved.