Friday, November 9, 2012

Changing the WCF Data Service request headers

The WCF Data Service client component works great out-of-the-box. However for a project we wanted to send some extra header data which each request. On the server-side we could handle this by adding a custom WCF behavior on top of the data service, but on the client side this is not possible.

How can we do this on the client side?

The MSDN site brought the answer: http://msdn.microsoft.com/en-us/library/gg258441.aspx

The DataServiceContext exposes a SendingRequest event. By subscribing to this even we can add a new header to the request message before it is sent to the data service.

// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);

// Register to handle the SendingRequest event.
context.SendingRequest += new EventHandler<SendingRequestEventArgs>(OnSendingRequest);


The following method handles the SendingRequest event and adds an Authentication header to the request.



private static void OnSendingRequest(object sender, SendingRequestEventArgs e)
{
// Add an Authorization header that contains an OAuth WRAP access token to the request.
e.RequestHeaders.Add("Authorization", "WRAP access_token=\"123456789\"");
}

No comments: