Access Session in Web API 2 MVC 5

How To Access Session Variables in Web API 2 Controller in ASP.Net MVC 5?

Accessing Session Using ASP.NET Web API 2 in MVC 5 -

Well, as you know, REST API by design is stateless. By adding session variables you are making it stateful and defeating any purpose of having a RESTful API.

In WebApi 2 you can add this to Global.asax
//Global.asax
protected void Application_PostAuthorizeRequest()
{
   System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}


Then you could access the session through
namespace demo.Api
{
    [EnableCors(origins: "http://localhost:53865,https://app.code-sample.com", headers: "*", methods: "*")]
    public class BaseAPIController : ApiController
    {
        /// <summary>
        /// BaseAPIController constructor will check that identity exists or not.
        /// </summary>
        public BaseAPIController()
        {
            //GET Current Session.
            var session = System.Web.HttpContext.Current.Session;

            if (!(HttpContext.Current.User.Identity.IsAuthenticated))
            {
                SetHeader();
            }
        }

        /// <summary>
        /// Set header status code to 401
        /// </summary>
        public void SetHeader()
        {
            HttpResponse resp = HttpContext.Current.Response;
            resp.StatusCode = 401;
            resp.End();
        }
    }
}


References -

I hope you are enjoying with this post! Please share with you friends. Thank you!!
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

How To Access Session Variables in Web API 2 Controller in ASP.Net MVC 5? How To Access Session Variables in Web API 2 Controller in ASP.Net MVC 5? Reviewed by Anil Singh on 4:04 AM Rating: (5)
www.code-sample.com/. Powered by Blogger.
^