How to use Session objects in an HttpHandler

In my previous post, Captcha using ASP.Net and C#, you may noticed that I am not talking about how can I validate the user is entering correct value or not. I thought of using Sessions for this purpose, like in the HTTP Handler, I wrote some code like

context.Session["captcha"] = drawString;

But that code failed, by throwing a Null Reference exception. After debugging I found the session object is coming as NULL. Then after doing a little search I found a nice post about how can we use session state in Http Handlers. For this you have to implement an empty interface, IRequiresSessionState, which in the available in the System.Web.SessionState namespace, you have to add reference of this namespace in your code, implement the interface, and you can use session in the Http Handler.

using System.Web.SessionState;

public class Handler : IHttpHandler, IRequiresSessionState
{
//Your implementation.
}

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

Now you can save the drawString value to the session state and in the C# code, you can read it from session and check with the user entry.

You can get more details from this post :How to use Session values in an HttpHandler

This entry was posted in .Net, .Net 3.0 / 3.5, ASP.Net, Visual Studio and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>