asp.net-mvc-2session-less

Sessionless ASP.NET MVC 2 requests have sessions yet


As we need Async Ajax requests, it is required to disable session state. Web app is based on ASP.Net 4 - MVC 2.

I am aware of [SessionState(SessionStateBehavior.Disabled)], however it is available in MVC 3+.

I am using the following method to route specific HTTP requests to a sessionless HTTPContext [source]:

public class CustomRouteHandler : IRouteHandler
    {
        public System.Web.IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            requestContext.HttpContext.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.ReadOnly);
            return new MvcHandler(requestContext);
        }
    }

And in Global.asax:

routes.MapRoute( _
          Nothing, _
          "ajaxrequest/{id}", _
          New With {.controller = "AjaxEngine", .action = "Index", .id = UrlParameter.Optional}, _
             New SessionLessRouteHandler()
        )

Result? The code compiles correctly, no errors in runtime. However, it does not change anything and in the HTTP Header of every single Ajax request I see a new set-cookie with a new session. For example, A browser may request 100 Ajax requests, and a new session will be generated for each request. And I never need a session for a static Ajax request. I see the following line in each Ajax request diagnosed by Chrome Network Monitor:

Set-Cookie:ASP.NET_SessionId=xlgxdzdxdeilws23prjns3cv; domain=mydomain.com; path=/

Any idea why it does not work? And how can I avoid creating a new session for the requests?


Solution

  • It was due to a mistake, routes.MapRoute accepts the new IRouteHandler, but it is inappropriate. You need to just set the RouteHandler using routes.Add instead of routes.MapRoute in Global.asax:

    routes.Add(Nothing, New Route("ajaxrequest/{id}", New 
        RouteValueDictionary(New With { _
        Key .controller = "AjaxEngine", _
        Key .action = "Index", _
        Key .id = UrlParameter.Optional _
        }), New SessionLessRouteHandler()))
    

    NOTE: By using ReadOnly sessionstate it continues to set the cookie. It is required to set it as Disabled in the RouteHandler class we defined.