Ask the Expert

Supporting a session state across posts

How do I invoke a Web service that supports a session state and maintains the session across posts?

    Requires Free Membership to View

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.


This was first published in September 2004

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: