How to access Session information from HttpHandler (Ashx file)<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to access Session information from HttpHandler (Ashx file)

Posted on: October 18, 2011

You may pass manually the information but would it be easier if the http handler could read the session information?

This can be done with .Net Framework easily. In theory, this should not be a problem because the handler is in the server. It only needs to provide the session of the current user. To do, you need to use special interface that will allow you to reach this information.

This interface is called IReadOnlySessionState or IRequiresSessionState.

Here is an example:

1<% @ webhandler language="C#" class="MyClass" %>
2
3using System; using System.Web; using System.Web.SessionState;
4
5public class MyClass: IHttpHandler, IReadOnlySessionState { public bool IsReusable { get { return true; } }
6
7public void ProcessRequest(HttpContext ctx) { ctx.Response.Write(ctx.Session["ID"]); } }

This example show you how to get the ID session's variable from the HttpHandler.

The second interface IRequiresSessionState is the same but will let you write also in the session.