Disable Session state per-request in ASP.Net Web Api (ApiController)

I have ApiControllers that access the session and by default has SessionState required. Therefore I am getting the requests serialized and would like to disable session state for specific requests.

In this post I have seen a solution for normal Controllers but I have no idea how to do it on ApiControllers.

This is my WebApiConfig

public static void Register(HttpConfiguration config)
    {
        RouteTable.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        ).RouteHandler = new SessionRouteHandler();

        config.Routes.MapHttpRoute(
            name: "Default2",
            routeTemplate: "api/{controller}"
        );
    }

And this is the SessionControllerHandler
public class SessionControllerHandler : HttpControllerHandler, IRequiresSessionState
{
    public SessionControllerHandler(RouteData routeData)
        : base(routeData)
    { }
}

public class SessionRouteHandler : IRouteHandler
{
    IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
    {
        return new SessionControllerHandler(requestContext.RouteData);
    }
}

Any help will be appreciated. Thank you

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

In order to not get the requests serialized, generate a new SessionControllerHandler for SessionState in ReadOnly mode

public class SessionControllerHandlerReadOnly : HttpControllerHandler, IReadOnlySessionState
{
    public SessionControllerHandlerReadOnly(RouteData routeData)
        : base(routeData)
    { }
}
public class SessionRouteHandlerReadOnly : IRouteHandler
{
    IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
    {
        return new SessionControllerHandlerReadOnly(requestContext.RouteData);
    }
}

Then in the WebApiConfig add a new route that uses that handler
RouteTable.Routes.MapHttpRoute(
            name: "DefaultApiReadOnly",
            routeTemplate: "apireadonly/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        ).RouteHandler = new SessionRouteHandlerReadOnly();

Done, when you need a specific request going through that handler you specify it in the RouteUrl when making the request
@Url.RouteUrl("DefaultApiReadOnly", new { httproute = true, controller = "controller", action = "action" })


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x