Search code examples
asp.netweb-servicessession-statewebmethodcookieless

Usage of web services with session-state cookieless=true


Enable sessions in a web service method like this:

[WebMethod(EnableSession=true)]
public string HelloWorld()
{
    return "Hello World";
}

Use a cookieless session state (web.config):

<sessionState cookieless="true"></sessionState>

Then try to call it from a client like this:

localhost.WebService1 ws1 = new localhost.WebService1();    // the web service proxy        
ws1.HelloWorld();

You get a redirect WebException (302) saying that the object has been moved:

enter image description here


Solution

  • A Microsoft article describes this issue: http://msdn.microsoft.com/en-us/library/aa480509.aspx

    The call from the client has to catch the WebException, and update the URL to the webservice, which has to include the sessionId generated by the web server. Then repeat the call to the method:

    localhost.WebService1 ws1 = new localhost.WebService1();    // the web service proxy    
    try {
        ws1.HelloWorld();
    } catch (WebException ex) {
        HttpWebResponse response = (HttpWebResponse)ex.Response;
        if (response.StatusCode == HttpStatusCode.Found) {
            ws1.Url = new Uri(new Uri(ws1.Url), response.Headers["Location"]).AbsoluteUri;
            ws1.HelloWorld();
        }
    }