Httpcontext.Current.Session Is Null in Ashx File

HttpContext.Current.Session is null in Ashx file

You must add on your handler the IRequiresSessionState on the declaration of it as:

public class YourHandleName : IHttpHandler, IRequiresSessionState 
{
...

by default the handlers are not connected with the session to keep them minimum, by adding the IRequiresSessionState you attach them with the session.

Asp.Net Session is null in ashx file

You have to "implement" either IRequiresSessionState or IReadOnlySessionState, with former providing full access to session, and the latter providing read-only access.

I'm quoting "implement" here because these two are so-called "marker interfaces", which means they have no members.

How do I set a session variable in an ASHX file

Make sure the handler implements System.Web.SessionState.IRequiresSessionState, just like in the link you provided.

You shouldn't need to have the HttpContext.Current part, if you import the namespace.

public class ImageHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
string Name = "";
if (context.Session["filename"] != null)
Name = context.Session["filename"].ToString();
}
}

HttpContext.Current.Session is null

It isn't really about including the State inside your class, but rather where you call it in your Global.asax. Session isn't available in all the methods.

A working example would be:

using System.Web.SessionState;

// ...

protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
{
HttpContext context = HttpContext.Current;
// Your Methods
}
}

It will not work e.g. in Application_Start

Sever.Transfer from ASHX handler, HttpContext.Current.Session is null

You got to mark handler with IRequiresSessionState marker interface in order to have Session initialized. If you only need to read from session use IReadOnlySessionState marker interface, so Session State Provider can skip saving session at the end of request. In case of out of proc Session State Provider that can give some gains in performance.

Here is the example :

using System.Web.SessionState;

namespace BlahBlah
{
public class CustomHandler : IHttpHandler, IRequiresSessionState
...
}

How to access Session in .ashx file?

In aspx file:

Session.Add("filename", "Test.txt");


After you have set session value in aspx file. Use following to get the value in ashx file.

In ashx file:

public class ImageHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
string Name = "";
if (context.Session["filename"] != null)
Name = context.Session["filename"].ToString();
}
}

What should I do if the current ASP.NET session is null?

Yes, the Session object might be null, but only in certain circumstances, which you will only rarely run into:

  • If you have disabled the SessionState http module, disabling sessions altogether
  • If your code runs before the HttpApplication.AcquireRequestState event.
  • Your code runs in an IHttpHandler, that does not specify either the IRequiresSessionState or IReadOnlySessionState interface.

If you only have code in pages, you won't run into this. Most of my ASP .NET code uses Session without checking for null repeatedly. It is, however, something to think about if you are developing an IHttpModule or otherwise is down in the grittier details of ASP .NET.

Edit

In answer to the comment: Whether or not session state is available depends on whether the AcquireRequestState event has run for the request. This is where the session state module does it's work by reading the session cookie and finding the appropiate set of session variables for you.

AcquireRequestState runs before control is handed to your Page. So if you are calling other functionality, including static classes, from your page, you should be fine.

If you have some classes doing initialization logic during startup, for example on the Application_Start event or by using a static constructor, Session state might not be available. It all boils down to whether there is a current request and AcquireRequestState has been run.

Also, should the client have disabled cookies, the Session object will still be available - but on the next request, the user will return with a new empty Session. This is because the client is given a Session statebag if he does not have one already. If the client does not transport the session cookie, we have no way of identifying the client as the same, so he will be handed a new session again and again.

How to access session in aspx that was modified in ashx?

I found the answer: When the handler is being called from FLASH (like swfupload or uploadify) it does not pass the current sessionid to the handler. The handler then creates a NEW session. To fix this, do the following:

Your UI: JavaScript:

$(Selector).uploadify({
swf: 'uploadify.swf',
uploader: 'Upload.ashx?ASPSESSID=<%=Session.SessionID%>'
});

Add to: Global.asax:

void Application_BeginRequest(object sender, EventArgs e)
{
try
{
string session_param_name = "ASPSESSID";
string session_cookie_name = "ASP.NET_SESSIONID";
string session_value = Request.Form[session_param_name] ?? Request.QueryString[session_param_name];
if (session_value != null) { UpdateCookie(session_cookie_name, session_value); }
}
catch (Exception) { }
}

void UpdateCookie(string cookie_name, string cookie_value)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
if (cookie == null)
{
HttpCookie cookie1 = new HttpCookie(cookie_name, cookie_value);
Response.Cookies.Add(cookie1);
}
else
{
cookie.Value = cookie_value;
HttpContext.Current.Request.Cookies.Set(cookie);
}
}

Taken & simplified for uploadify from:
http://snipplr.com/view/15180/

You may need to use an authid if using formsauthentication:

&AUTHID=<%= Request.Cookies[FormsAuthentication.FormsCookieName] == null ? "" : Request.Cookies[FormsAuthentication.FormsCookieName].Value %>

append that to the uploader parameter in the jQuery.

Then add the following to the global:

try
{
string auth_param_name = "AUTHID";
string auth_cookie_name = FormsAuthentication.FormsCookieName;
string auth_value = Request.Form[auth_param_name] ?? Request.QueryString[auth_param_name];

if (auth_value != null) { UpdateCookie(auth_cookie_name, auth_value); }
}
catch (Exception) { }

You can now access the same session from the handler (even using the static session object I used above in the question) in IE, Chrome, FF, ect.



Related Topics



Leave a reply



Submit