Accessing Session Using ASP.NET Web API

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

    I had this same problem in asp.net mvc, I fixed it by putting this method in my base api controller that all my api controllers inherit from:

        /// 
        /// Get the session from HttpContext.Current, if that is null try to get it from the Request properties.
        /// 
        /// 
        protected HttpContextWrapper GetHttpContextWrapper()
        {
          HttpContextWrapper httpContextWrapper = null;
          if (HttpContext.Current != null)
          {
            httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
          }
          else if (Request.Properties.ContainsKey("MS_HttpContext"))
          {
            httpContextWrapper = (HttpContextWrapper)Request.Properties["MS_HttpContext"];
          }
          return httpContextWrapper;
        }
    

    Then in your api call that you want to access the session you just do:

    HttpContextWrapper httpContextWrapper = GetHttpContextWrapper();
    var someVariableFromSession = httpContextWrapper.Session["SomeSessionValue"];
    

    I also have this in my Global.asax.cs file like other people have posted, not sure if you still need it using the method above, but here it is just in case:

    /// 
    /// The following method makes Session available.
    /// 
    protected void Application_PostAuthorizeRequest()
    {
      if (HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith("~/api"))
      {
        HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
      }
    }
    

    You could also just make a custom filter attribute that you can stick on your api calls that you need session, then you can use session in your api call like you normally would via HttpContext.Current.Session["SomeValue"]:

      /// 
      /// Filter that gets session context from request if HttpContext.Current is null.
      /// 
      public class RequireSessionAttribute : ActionFilterAttribute
      {
        /// 
        /// Runs before action
        /// 
        /// 
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
          if (HttpContext.Current == null)
          {
            if (actionContext.Request.Properties.ContainsKey("MS_HttpContext"))
            {
              HttpContext.Current = ((HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).ApplicationInstance.Context;
            }
          }
        }
      }
    

    Hope this helps.

提交回复
热议问题