Tuesday 8 January 2013

HttpHandlers and Session State

By default, if you create a new HttpHandler, it does not have access to the session object. Take the following as a very simple example:


public class MyHandler : IHttpHandler
{
    #region IHttpHandler Members

    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        string s = (string)context.Session["MySessionObject"];
        context.Response.Write(s);
    }

    #endregion
}


Do you see the problem? HttpContext.Current.Session will be null and an exception will be thrown.

So, how do you access the Session object from within an HttpHandler? I've tried all sorts of magical workarounds, some worked, some didn't but by far the easiest is just to simply add the IReadOnlySessionState interface to your handler, so it'll look like this:


public class MyHandler IHttpHandler, IReadOnlySessionState
{
    #region IHttpHandler Members

    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        string s = (string)context.Session["MySessionObject"];
        context.Response.Write(s);
    }

    #endregion
}


And as if by magic, your session object is populated and you can access your session objects like you usually would. Fantastic news! You can't write to the session object by the way, but I've not come across a scenario where I've needed to yet.

Thanks to Scott Hansleman's blog for the solution to that little problem!

No comments:

Post a Comment