Custom Cookie Handling
Cookies are the de facto correlation protocol for web applications, which means HTTP applications rather than SOAP. Most uses of cookies in web services are quite simplistic with the standard cookie container behavior sufficiently up to the task of handling the exchange. Today's article covers the times when the automatic cookie handling behavior is insufficient.
To get started with custom cookie handling you first need to turn off cookies. This may sound terribly confusing but that's because the AllowCookies property is so badly named. This property controls whether a CookieContainer is setup and used to automatically copy cookies around and set the value of the Cookie header. It should really be called the AutomaticCookieHandling property. You would probably understand what was going on if the instructions said "to get custom control over cookie handling, set the AutomaticCookieHandling property to false". Instead, the instructions say to set the AllowCookies property to false.
Once you've turned off automatic cookie handling, you have free access to the cookie headers on incoming and outgoing messages using the standard HTTP message properties. Here's some uninteresting code for a client showing bouncing a cookie off of a server.
using (new OperationContextScope(client.InnerChannel))
{
HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();
requestProperty.Headers.Add("Cookie", "MyCookie=value");
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty;
client.DoOperation();
MessageProperties properties = OperationContext.Current.IncomingMessageProperties;
HttpResponseMessageProperty responseProperty = (HttpResponseMessageProperty)properties[HttpResponseMessageProperty.Name];
string cookieHeader = responseProperty.Headers[HttpResponseHeader.SetCookie];
}
Code on the server would look very similar with the roles of Cookie and Set-Cookie reversed.
Next time: Controlling Certificate Validation
Comments
Anonymous
January 17, 2008
I want to provide some additional information about the user within the client credentials. Can I doAnonymous
February 08, 2008
By request I expanded the code in the earlier article on custom cookie handling to show a more interestingAnonymous
April 25, 2008
How do I manually manage the context when sharing a client object? The default mode when using a context