[c#] HttpContext.Current.Session is null when routing requests

Without routing, HttpContext.Current.Session is there so I know that the StateServer is working. When I route my requests, HttpContext.Current.Session is null in the routed page. I am using .NET 3.5 sp1 on IIS 7.0, without the MVC previews. It appears that AcquireRequestState is never fired when using the routes and so the session variable isn't instantiated/filled.

When I try to access the Session variables, I get this error:

base {System.Runtime.InteropServices.ExternalException} = {"Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>.

While debugging, I also get the error that the HttpContext.Current.Session is not accessible in that context.

--

My web.config looks like this:

<configuration>
  ...
  <system.web>
    <pages enableSessionState="true">
      <controls>
        ...
      </controls>
    </pages>
    ...
  </system.web>
  <sessionState cookieless="AutoDetect" mode="StateServer" timeout="22" />
  ...
</configuration>

Here's the IRouteHandler implementation:

public class WebPageRouteHandler : IRouteHandler, IRequiresSessionState
{
    public string m_VirtualPath { get; private set; }
    public bool m_CheckPhysicalUrlAccess { get; set; }

    public WebPageRouteHandler(string virtualPath) : this(virtualPath, false)
    {
    }
    public WebPageRouteHandler(string virtualPath, bool checkPhysicalUrlAccess)
    {
        m_VirtualPath = virtualPath;
        m_CheckPhysicalUrlAccess = checkPhysicalUrlAccess;
    }

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        if (m_CheckPhysicalUrlAccess
            && !UrlAuthorizationModule.CheckUrlAccessForPrincipal(
                   m_VirtualPath,
                   requestContext.HttpContext.User,
                   requestContext.HttpContext.Request.HttpMethod))
        {
            throw new SecurityException();
        }

        string var = String.Empty;
        foreach (var value in requestContext.RouteData.Values)
        {
            requestContext.HttpContext.Items[value.Key] = value.Value;
        }

        Page page = BuildManager.CreateInstanceFromVirtualPath(
                        m_VirtualPath, 
                        typeof(Page)) as Page;// IHttpHandler;

        if (page != null)
        {
            return page;
        }
        return page;
    }
}

I've also tried to put EnableSessionState="True" on the top of the aspx pages but still, nothing.

Any insights? Should I write another HttpRequestHandler that implements IRequiresSessionState?

Thanks.

This question is related to c# asp.net routing session-variables

The answer is


What @Bogdan Maxim said. Or change to use InProc if you're not using an external sesssion state server.

<sessionState mode="InProc" timeout="20" cookieless="AutoDetect" />

Look here for more info on the SessionState directive.


a better solution is

runAllManagedModulesForAllRequest is a clever thing to do respect removing and resinserting session module.

alk.


What @Bogdan Maxim said. Or change to use InProc if you're not using an external sesssion state server.

<sessionState mode="InProc" timeout="20" cookieless="AutoDetect" />

Look here for more info on the SessionState directive.


I was missing a reference to System.web.mvc dll in the session adapter, and adding the same fixed the issue.

Hopefully it will help someone else going through same scenario.


Just add attribute runAllManagedModulesForAllRequests="true" to system.webServer\modules in web.config.

This attribute is enabled by default in MVC and Dynamic Data projects.


I think this part of code make changes to the context.

 Page page = BuildManager.CreateInstanceFromVirtualPath(
                        m_VirtualPath, 
                        typeof(Page)) as Page;// IHttpHandler;

Also this part of code is useless:

 if (page != null)
 {
     return page;
 }
 return page;

It will always return the page wither it's null or not.


It seems that you have forgotten to add your state server address in the config file.

 <sessionstate mode="StateServer" timeout="20" server="127.0.0.1" port="42424" />

Just add attribute runAllManagedModulesForAllRequests="true" to system.webServer\modules in web.config.

This attribute is enabled by default in MVC and Dynamic Data projects.


None of these solutions worked for me. I added the following method into global.asax.cs then Session was not null:

protected void Application_PostAuthorizeRequest()
{
    HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}

Nice job! I've been having the exact same problem. Adding and removing the Session module worked perfectly for me too. It didn't however bring back by HttpContext.Current.User so I tried your little trick with the FormsAuth module and sure enough, that did it.

<remove name="FormsAuthentication" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>

I think this part of code make changes to the context.

 Page page = BuildManager.CreateInstanceFromVirtualPath(
                        m_VirtualPath, 
                        typeof(Page)) as Page;// IHttpHandler;

Also this part of code is useless:

 if (page != null)
 {
     return page;
 }
 return page;

It will always return the page wither it's null or not.


Nice job! I've been having the exact same problem. Adding and removing the Session module worked perfectly for me too. It didn't however bring back by HttpContext.Current.User so I tried your little trick with the FormsAuth module and sure enough, that did it.

<remove name="FormsAuthentication" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>

Just add attribute runAllManagedModulesForAllRequests="true" to system.webServer\modules in web.config.

This attribute is enabled by default in MVC and Dynamic Data projects.


Nice job! I've been having the exact same problem. Adding and removing the Session module worked perfectly for me too. It didn't however bring back by HttpContext.Current.User so I tried your little trick with the FormsAuth module and sure enough, that did it.

<remove name="FormsAuthentication" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>

None of these solutions worked for me. I added the following method into global.asax.cs then Session was not null:

protected void Application_PostAuthorizeRequest()
{
    HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}

I think this part of code make changes to the context.

 Page page = BuildManager.CreateInstanceFromVirtualPath(
                        m_VirtualPath, 
                        typeof(Page)) as Page;// IHttpHandler;

Also this part of code is useless:

 if (page != null)
 {
     return page;
 }
 return page;

It will always return the page wither it's null or not.


It seems that you have forgotten to add your state server address in the config file.

 <sessionstate mode="StateServer" timeout="20" server="127.0.0.1" port="42424" />

runAllManagedModulesForAllRequests=true is actually a real bad solution. This increased the load time of my application by 200%. The better solution is to manually remove and add the session object and to avoid the run all managed modules attribute all together.


I think this part of code make changes to the context.

 Page page = BuildManager.CreateInstanceFromVirtualPath(
                        m_VirtualPath, 
                        typeof(Page)) as Page;// IHttpHandler;

Also this part of code is useless:

 if (page != null)
 {
     return page;
 }
 return page;

It will always return the page wither it's null or not.


What @Bogdan Maxim said. Or change to use InProc if you're not using an external sesssion state server.

<sessionState mode="InProc" timeout="20" cookieless="AutoDetect" />

Look here for more info on the SessionState directive.


The config section seems sound as it works if when pages are accessed normally. I've tried the other configurations suggested but the problem is still there.

I doubt the problem is in the Session provider since it works without the routing.


Just add attribute runAllManagedModulesForAllRequests="true" to system.webServer\modules in web.config.

This attribute is enabled by default in MVC and Dynamic Data projects.


It seems that you have forgotten to add your state server address in the config file.

 <sessionstate mode="StateServer" timeout="20" server="127.0.0.1" port="42424" />

Nice job! I've been having the exact same problem. Adding and removing the Session module worked perfectly for me too. It didn't however bring back by HttpContext.Current.User so I tried your little trick with the FormsAuth module and sure enough, that did it.

<remove name="FormsAuthentication" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>

I was missing a reference to System.web.mvc dll in the session adapter, and adding the same fixed the issue.

Hopefully it will help someone else going through same scenario.


The config section seems sound as it works if when pages are accessed normally. I've tried the other configurations suggested but the problem is still there.

I doubt the problem is in the Session provider since it works without the routing.


runAllManagedModulesForAllRequests=true is actually a real bad solution. This increased the load time of my application by 200%. The better solution is to manually remove and add the session object and to avoid the run all managed modules attribute all together.


The config section seems sound as it works if when pages are accessed normally. I've tried the other configurations suggested but the problem is still there.

I doubt the problem is in the Session provider since it works without the routing.


It seems that you have forgotten to add your state server address in the config file.

 <sessionstate mode="StateServer" timeout="20" server="127.0.0.1" port="42424" />

a better solution is

runAllManagedModulesForAllRequest is a clever thing to do respect removing and resinserting session module.

alk.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to routing

Send data through routing paths in Angular Angular2 Routing with Hashtag to page anchor Passive Link in Angular 2 - <a href=""> equivalent laravel throwing MethodNotAllowedHttpException How to use absolute path in twig functions S3 Static Website Hosting Route All Paths to Index.html AngularJS - How can I do a redirect with a full page load? Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id} The requested resource does not support HTTP method 'GET' My Routes are Returning a 404, How can I Fix Them?

Examples related to session-variables

Local storage in Angular 2 Set session variable in laravel Session variables not working php Setting session variable using javascript How to use sessions in an ASP.NET MVC 4 application? Check if PHP session has already started How to use store and use session variables across pages? MySQL wait_timeout Variable - GLOBAL vs SESSION How do servlets work? Instantiation, sessions, shared variables and multithreading How to empty/destroy a session in rails?