Search code examples
c#asp.netweb-servicesashx

Session.SessionId persistence in requests to ashx


when i make a webrequest call to a service, why does it always generates a new sessionid?

This is how i call from sitea.com

WebClient fs = new WebClient();
            var data = fs.DownloadData("http://siteb.com/serice.ashx");
            var tostring = System.Text.Encoding.ASCII.GetString(data);
            return tostring;

This is the service code at siteb.com

[WebMethod(EnableSession = true)]
    private string Read(HttpContext context)
    {
        var value = context.Session.SessionId;
        if (value !=null) return value.ToString();
            return "false";
    }

value is always different for every request. How can i persist this?


Solution

  • You have to receive session id and pass it to subsequent requests. By default, it will be sent in a cookie, but WebClient doesn't handle cookies. You can use CookieAwareWebClient to solve this:

    public class CookieAwareWebClient : WebClient
    {
        private CookieContainer m_container = new CookieContainer();
    
        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                (request as HttpWebRequest).CookieContainer = m_container;
            }
            return request;
        }
    }
    

    As long as you're reusing the same instance of web client, you should get the same session id (if the session won't time out of course).