Enabling Cookies in Windows Phone WCF Client Applications
January 24, 2014If you are a developing a Windows Phone app that communicates with a WCF Service, chances are you need to enable cookies on your service client in order to maintain session state and keep being logged in.
Developing a Windows Phone application, I recently ran into the problem that the WCF service my app was using kept rejecting my service calls even though I had logged in correctly before. The reason for this was missing cookie information in the HTTP headers my service client was sending and the WCF service was relying on these in order to maintain session state and keep me logged in.
Fortunately, there is an easy solution for that and you do not have to tweak and fiddle with cookies and HTTP headers manually. Two simple steps will solve this issue:
- First, enable HTTP cookies in your client-side WCF configuration (a file usually called ServiceReferences.ClientConfig). The attribute enableHttpCookieContainer needs to be set to true for this.
<bindings> <basicHttpBinding> <binding name="ServiceExtSoap" enableHttpCookieContainer="true"> <security mode="None" /> </binding> </basicHttpBinding> </bindings>
- Second, create a CookieContainer object on your service client.
var serviceClient = new ServiceExtSoapClient(); serviceClient.CookieContainer = new CookieContainer();
That’s all there is:session state sent from the server is now handled automatically by your WCF client.