Session is null in Generic Handler (ashx)

System.NullReferenceException (“Object reference not set to an instance of an object”) is thrown when you try to read/write the Session object in a generic handler without implementing System.Web.SessionState.IRequiresSessionState.

If your intention is to read only, then use IReadOnlySessionState instead.

Example:

<%@ WebHandler Language="C#" Class="MyHandler" %>

using System;
using System.Web;

public class MyHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s