Channafow Channafow - 5 months ago 20
Ajax Question

Session-less HttpHandler and routing to custom handler for only one controller .NET

We have an web app that will make an AJAX call to the server every 30 seconds to update a value in a page. The app itself is a mixture of MVC and webforms (part of the app was upgraded to MVC while the other is still legacy). The issue with the AJAX call is that it will reset the session timeout essentially never allowing the user to timeout. A work around I found was from this answer (Disable Session state per-request in ASP.Net MVC) which is to create a new handler that does not use Session. That should solve the issue.

Though my second problem is that it does not seem as though the application is following my new routing rule for the only controller that uses this "session-less" handler:

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "FirstController", action = "Index", id = UrlParameter.Optional }
);
routes.Add("Sessionless", new Route("SessionlessController/SessionlessAction/{id}",
new RouteValueDictionary(new { id= UrlParameter.Optional }),
new SessionlessHandler()));


I have a breakpoint on my handler, though the app does not seem to go to the handler:

public class SessionlessHandler: IRouteHandler {
public IHttpHandler GetHttpHandler(RequestContext requestContext) {
return null;
}
}


I want it that only my "session-less" controller will use this custom handler and all other controls use default.

Answer

You need to reverse the order of your routes so the most specific route executes before your general Default route.

routes.Add("Sessionless", new Route("SessionlessController/SessionlessAction/{id}",
        new RouteValueDictionary(new { id= UrlParameter.Optional }),
        new SessionlessHandler()));

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "FirstController", action = "Index", id = UrlParameter.Optional }
);

See Why map special routes first before common routes in asp.net mvc for a complete explanation.

Comments