How do I invoke a Web service that supports a session state and maintains the session across posts? The Web service
proxy class, which derives from SoapHttpClientProtocol, has a property called CookieContainer. If you intialize this to an instance of the System.Net.CookieContainer type, it will store cookies returned to the client. When the same proxy, with the same instance of the cookie container, is used to invoke service methods, the proxy serializes cookies in the cookie container with the reqest, as a properly formed HTTP header. Before calling methods that support session state, be sure to create the CookieContainer and initialize the proxy like so:
System.Net.CookieContainer cookies = new System.Net.CookieContainer(); localhost.SessionService1 svc = new localhost.SessionService1(); svc.CookieContainer = cookies; svc.UpdateHitCounter();For a working demo, download the example here.
Be sure and note that a single instance of the cookie container is scoped for the lifetime of the application. If you assign a new cookie container to the proxy, previously stored session ID (or, other cookies) will not be passed with the request.
NOTE: I don't generally recommend using session state with Web services. The typical argument for its use is to support login-once scenarios. However, to maintain a logged in state this way, there isn't sufficient security to prevent replay attacks or sniffing session ID from the wire. OASIS WS-Security specifications describe how to safely pass tokens, including session-based tokens that have adequate expiry rules. Furthermore, they describe how to encrypt and sign the message to be sure no tampering has been done. For other types of session-based tokens, see WS-SecureConversation, WS-Trust and SAML specifications.
To comment on this or ask follow up questions see my web log entry.
Dig deeper on Microsoft .NET Web services
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.