Accessing Session Using ASP.NET Web API

前端 未结 13 944
谎友^
谎友^ 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: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

提交回复
热议问题