December, 2010 browsing by month


Use Session in Generic Handler file (.ashx)

Sunday, December 12th, 2010

Using Generic Handler or .ashx file instead of heavyset web form (.aspx) is a lighter-weight and faster way to handle certain types of Http request, such as rendering an large image, spit out text files, etc. I recently used it in one web project that needed to setup a Http listener to process incoming requests and not doing any Html rendering.

By default, an .ashx file (Generic Handler template from VS2010) code behind automatically added these namespaces only:


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;


Then when I tried to store a session_id from incoming Http request’s querystring in the Session object of HttpContext.Current, and it failed. As it turned out, in order to access Session object, I needed to add a SessionState namespace, System.web.SessionState; and then implement theĀ IRequiresSessionState interface. the beginning of the .ashx code behind now looked like this:



public class ServeRequest : IHttpHandler, IRequiresSessionState



public void ProcessRequest(HttpContext context)



//codes to handle Http request