web analytics

How to use Session objects in an ASP.NET HttpHandler?

Options

codeling 1602 - 6666
@2016-01-08 12:27:25

To use session state in HTTP Handlers in ASP.NET, you have to implement an empty interface: IRequiresSessionState, which in the available in the System.Web.SessionState namespace, otherwise, you will get a Null Reference exception.

IRequiresSessionState interface specifies that the target HTTP handler requires read and write access to session-state values. This is a marker interface and has no methods.

The following code shows you how to do that.

using System;
using System.Xml;
using System.Web;
using System.Web.SessionState;

namespace HttpHandlerDemo
{
    public class XmlHandler : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext ctx)
        {
            int sum = Int32.Parse(ctx.Request.QueryString["x"]);
            sum += Int32.Parse(ctx.Request.QueryString["y"]);
            ctx.Response.ContentType = "text/xml";
            ctx.Session["sum"] = sum;

            XmlTextWriter w = new XmlTextWriter(ctx.Response.Output);
            w.WriteElementString("Sum", sum.ToString());
            w.Close();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 

You can also use IReadOnlySessionState interface instead of IRequiresSessionState, which gives read only access to the session objects.
 

Package the above code in a separate assembly and register the handler in your web.config. You have to specify to which URL(s) this handler belongs, but you could also use a wildcard such as *.xml.

<configuration>
  <system.webServer>
    <handlers>
      <add verb="*" path="Add.xml" type="HttpHandlerDemo.XmlHandler, HttpHandlerDemo"/>
    </handlers>
  </system.webServer>
</configuration>

You can now call this handler by browsing to the following URL:

http://server/app/Add.xml?x=50&y=50

The result look like the following figure:

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com