Accessing Session Using ASP.NET Web API

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

    I followed @LachlanB approach and indeed the session was available when the session cookie was present on the request. The missing part is how the Session cookie is sent to the client the first time?

    I created a HttpModule which not only enabling the HttpSessionState availability but also sends the cookie to the client when a new session is created.

    public class WebApiSessionModule : IHttpModule
    {
        private static readonly string SessionStateCookieName = "ASP.NET_SessionId";
    
        public void Init(HttpApplication context)
        {
            context.PostAuthorizeRequest += this.OnPostAuthorizeRequest;
            context.PostRequestHandlerExecute += this.PostRequestHandlerExecute;
        }
    
        public void Dispose()
        {
        }
    
        protected virtual void OnPostAuthorizeRequest(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
    
            if (this.IsWebApiRequest(context))
            {
                context.SetSessionStateBehavior(SessionStateBehavior.Required);
            }
        }
    
        protected virtual void PostRequestHandlerExecute(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
    
            if (this.IsWebApiRequest(context))
            {
                this.AddSessionCookieToResponseIfNeeded(context);
            }
        }
    
        protected virtual void AddSessionCookieToResponseIfNeeded(HttpContext context)
        {
            HttpSessionState session = context.Session;
    
            if (session == null)
            {
                // session not available
                return;
            }
    
            if (!session.IsNewSession)
            {
                // it's safe to assume that the cookie was
                // received as part of the request so there is
                // no need to set it
                return;
            }
    
            string cookieName = GetSessionCookieName();
            HttpCookie cookie = context.Response.Cookies[cookieName];
            if (cookie == null || cookie.Value != session.SessionID)
            {
                context.Response.Cookies.Remove(cookieName);
                context.Response.Cookies.Add(new HttpCookie(cookieName, session.SessionID));
            }
        }
    
        protected virtual string GetSessionCookieName()
        {
            var sessionStateSection = (SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");
    
            return sessionStateSection != null && !string.IsNullOrWhiteSpace(sessionStateSection.CookieName) ? sessionStateSection.CookieName : SessionStateCookieName;
        }
    
        protected virtual bool IsWebApiRequest(HttpContext context)
        {
            string requestPath = context.Request.AppRelativeCurrentExecutionFilePath;
    
            if (requestPath == null)
            {
                return false;
            }
    
            return requestPath.StartsWith(WebApiConfig.UrlPrefixRelative, StringComparison.InvariantCultureIgnoreCase);
        }
    }
    

提交回复
热议问题