locked
Session state variable usage in web api RRS feed

  • Question

  • User1194656299 posted

    Hi

    I am trying to use session variables in my web api non mvc application.

    I have enabled session in global.aspx page as

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

    Now in my controller

    public class AuthenticateController : ApiController
    {
    [Route("api/CheckLogin")]
    public string AuthenticateUser(Models.Customer customer)
    {
    
    HttpContextBase context = null;
    var httpContext = context as HttpContextBase;
    httpContext.Session["username"] = "sa";
    
    }



    But I am getting null ref error.

    How can I achieve this

    Please help

    Tuesday, April 19, 2016 4:10 PM

Answers

  • User36583972 posted

    Hi sajilprasad,

    From your description, I suggest you can use the following code to implement session state in Web API.

    Define SessionableControllerHandler  and SessionStateRouteHandler class:

    public class SessionableControllerHandler : HttpControllerHandler, IRequiresSessionState
        {
            public SessionableControllerHandler(RouteData routeData)
                : base(routeData)
            { }
        }
    
        public class SessionStateRouteHandler : IRouteHandler
        {
            IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
            {
                return new SessionableControllerHandler(requestContext.RouteData);
            }
        }

    Comment out the Web API route definition as follows:
    WebApiConfig.cs:

                // Moved to RouteConfig.cs to enable Session
                /*
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
                 */

    RouteConfig.cs:

        public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
    
                // Web API Stateless Route Configurations
                routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                ).RouteHandler = new SessionStateRouteHandler();
    
    
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                );
    
                //// Web API Session Enabled Route Configurations
                //routes.MapHttpRoute(
                //    name: "SessionsRoute",
                //    routeTemplate: "api/sessions/{controller}/{id}",
                //    defaults: new { id = RouteParameter.Optional }
                //).RouteHandler = new SessionStateRouteHandler(); ;
    
              
            }
        }

    API method:

            // GET api/values
            [AllowAnonymous]
            public string Get()
            {
                var session = HttpContext.Current.Session;
                if (session != null)
                {
                    if (session["username"] == null)
                        session["username"] = "sa:" + DateTime.Now.ToString();
                    return session["username"].ToString();
                }else
                {
                    return "session error!";
                }
            }

    Error:

    OK:

    You can refer the following tutorial.

    Providing session state in ASP.NET WebAPI:

    http://www.codeproject.com/Tips/513522/Providing-session-state-in-ASP-NET-WebAPI

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 20, 2016 8:01 AM

All replies

  • User527778624 posted

    Hi,

    Check this site for correct way to enable session for webapi:

    http://stackoverflow.com/questions/11478244/asp-net-web-api-session-or-something

    Tuesday, April 19, 2016 6:05 PM
  • User36583972 posted

    Hi sajilprasad,

    From your description, I suggest you can use the following code to implement session state in Web API.

    Define SessionableControllerHandler  and SessionStateRouteHandler class:

    public class SessionableControllerHandler : HttpControllerHandler, IRequiresSessionState
        {
            public SessionableControllerHandler(RouteData routeData)
                : base(routeData)
            { }
        }
    
        public class SessionStateRouteHandler : IRouteHandler
        {
            IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
            {
                return new SessionableControllerHandler(requestContext.RouteData);
            }
        }

    Comment out the Web API route definition as follows:
    WebApiConfig.cs:

                // Moved to RouteConfig.cs to enable Session
                /*
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
                 */

    RouteConfig.cs:

        public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
    
                // Web API Stateless Route Configurations
                routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                ).RouteHandler = new SessionStateRouteHandler();
    
    
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                );
    
                //// Web API Session Enabled Route Configurations
                //routes.MapHttpRoute(
                //    name: "SessionsRoute",
                //    routeTemplate: "api/sessions/{controller}/{id}",
                //    defaults: new { id = RouteParameter.Optional }
                //).RouteHandler = new SessionStateRouteHandler(); ;
    
              
            }
        }

    API method:

            // GET api/values
            [AllowAnonymous]
            public string Get()
            {
                var session = HttpContext.Current.Session;
                if (session != null)
                {
                    if (session["username"] == null)
                        session["username"] = "sa:" + DateTime.Now.ToString();
                    return session["username"].ToString();
                }else
                {
                    return "session error!";
                }
            }

    Error:

    OK:

    You can refer the following tutorial.

    Providing session state in ASP.NET WebAPI:

    http://www.codeproject.com/Tips/513522/Providing-session-state-in-ASP-NET-WebAPI

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 20, 2016 8:01 AM