Accessing Session Using ASP.NET Web API

前端 未结 13 940
谎友^
谎友^ 2020-11-22 04:32

I realize session and REST don\'t exactly go hand in hand but is it not possible to access session state using the new Web API? HttpContext.Current.Session is a

相关标签:
13条回答
  • 2020-11-22 05:04

    Yes, session doesn't go hand in hand with Rest API and also we should avoid this practices. But as per requirements we need to maintain session somehow such that in every request client server can exchange or maintain state or data. So, the best way to achieve this without breaking the REST protocols is communicate through token like JWT.

    https://jwt.io/

    0 讨论(0)
  • 2020-11-22 05:07

    Following on from LachlanB's answer, if your ApiController doesn't sit within a particular directory (like /api) you can instead test the request using RouteTable.Routes.GetRouteData, for example:

    protected void Application_PostAuthorizeRequest()
        {
            // WebApi SessionState
            var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));
            if (routeData != null && routeData.RouteHandler is HttpControllerRouteHandler)
                HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
        }
    
    0 讨论(0)
  • 2020-11-22 05:11

    To fix the issue:

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

    in Global.asax.cs

    0 讨论(0)
  • 2020-11-22 05:12

    one thing need to mention on @LachlanB 's answer.

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

    If you omit the line if (IsWebApiRequest())

    The whole site will have page loading slowness issue if your site is mixed with web form pages.

    0 讨论(0)
  • 2020-11-22 05:13

    Last one is not working now, take this one, it worked for me.

    in WebApiConfig.cs at App_Start

        public static string _WebApiExecutionPath = "api";
    
        public static void Register(HttpConfiguration config)
        {
            var basicRouteTemplate = string.Format("{0}/{1}", _WebApiExecutionPath, "{controller}");
    
            // Controller Only
            // To handle routes like `/api/VTRouting`
            config.Routes.MapHttpRoute(
                name: "ControllerOnly",
                routeTemplate: basicRouteTemplate//"{0}/{controller}"
            );
    
            // Controller with ID
            // To handle routes like `/api/VTRouting/1`
            config.Routes.MapHttpRoute(
                name: "ControllerAndId",
                routeTemplate: string.Format ("{0}/{1}", basicRouteTemplate, "{id}"),
                defaults: null,
                constraints: new { id = @"^\d+$" } // Only integers 
            );
    

    Global.asax

    protected void Application_PostAuthorizeRequest()
    {
      if (IsWebApiRequest())
      {
        HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
      }
    }
    
    private static bool IsWebApiRequest()
    {
      return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(_WebApiExecutionPath);
    }
    

    fournd here: http://forums.asp.net/t/1773026.aspx/1

    0 讨论(0)
  • 2020-11-22 05:14

    Why to avoid using Session in WebAPI?

    Performance, performance, performance!

    There's a very good, and often overlooked reason why you shouldn't be using Session in WebAPI at all.

    The way ASP.NET works when Session is in use is to serialize all requests received from a single client. Now I'm not talking about object serialization - but running them in the order received and waiting for each to complete before running the next. This is to avoid nasty thread / race conditions if two requests each try to access Session simultaneously.

    Concurrent Requests and Session State

    Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished. (The second session can also get access if the exclusive lock on the information is freed because the first request exceeds the lock time-out.) If the EnableSessionState value in the @ Page directive is set to ReadOnly, a request for the read-only session information does not result in an exclusive lock on the session data. However, read-only requests for session data might still have to wait for a lock set by a read-write request for session data to clear.

    So what does this mean for Web API? If you have an application running many AJAX requests then only ONE is going to be able to run at a time. If you have a slower request then it will block all others from that client until it is complete. In some applications this could lead to very noticeably sluggish performance.

    So you should probably use an MVC controller if you absolutely need something from the users session and avoid the unncesessary performance penalty of enabling it for WebApi.

    You can easily test this out for yourself by just putting Thread.Sleep(5000) in a WebAPI method and enable Session. Run 5 requests to it and they will take a total of 25 seconds to complete. Without Session they'll take a total of just over 5 seconds.

    (This same reasoning applies to SignalR).

    0 讨论(0)
提交回复
热议问题