HttpContext.Current.Session is null in Ashx file
Asked Answered
G

1

45

I saw some questions (Here and Here) but they do not answer my question. I am trying to call Ajax using "ajax.ashx" file, and in function to access Session. For some reason, the value of the Session object itself is null.

Use example:

Session = HttpContext.Current.Session // This is null

Or:

public virtual void ProcessRequest(HttpContext context)
{
    System.Web.SessionState.HttpSessionState Session = context.Session; 
    // This is null
}

In the Web.config:

<sessionState timeout="1800"></sessionState>
Gallinacean answered 6/1, 2013 at 10:54 Comment(1)
Possible duplicate of #2157024, but this has good answer and comments also.Packer
P
104

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.

Plurality answered 6/1, 2013 at 11:16 Comment(4)
Note that this can be inherited too, if all your .ASHX.CS classes inherit from the same class, and that class has the IRequiresSessionState interface you'll also be able to access the current session in each handler.Brutality
@StevendeSalas Ok, but just for your knowledge, is better to avoid session if you can, and especial on handlers, because the page or handler that request the session is lock the entire site calls until ends #11630100Plurality
Moving from asp.net website to web app has caused this for me. I had to add the IRequiresSessionState to make it work. It worked fine in the asp.net website before going to web app.Iow
To use "IRequiresSessionState" we need to include the "using System.Web.SessionState;" instruction, just add a bit more details.Brinna

© 2022 - 2024 — McMap. All rights reserved.