.NET Web API + Session Timeout
asp.net-web-api, c#, session-state
Solution
This is by design in Web API because it is designed for creating restful web services. To be truly restful a service should not have any kind of state, i.e. `/myserver/somendpoint/5` should have the same result for any request with a given verb.
However if that doesn't suit you, you can enable session in web API by adding following to global.asax.
protected void Application_PostAuthorizeRequest()
{
System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}
Problem
I am creating a web service with web api controller. I want to be able to create a session and check the status of the session. I have the following: Controller: ``` public string Get(string user, string pass) { bool loginValue = false; loginValue = UserNamepassword(user, pass); if (loginValue == true) { HttpContext.Current.Session.Add("Username", user); //session["Username"] = user; //session.Add("Username", user); if ((string)HttpContext.Current.Session["Username"] != null) { HttpContext.Current.Session.Add("Time", DateTime.Now); return "Username: " + (string)HttpContext.Current.Session["Time"] + (string)HttpContext.Current.Session["Username"]; } return "Logged in but session is not availabe for " + (string)HttpContext.Current.Session["Username"]; } else return "Login failed for " + user; } ``` WebConfig ``` public static void RegisterRoutes(RouteCollection routes) { var route = routes.MapHttpRoute( name: "SessionApi", routeTemplate: "api/{controller}/{user}/{pass}", defaults: new { user = RouteParameter.Optional, pass = RouteParameter.Optional } ); route.RouteHandler = new MyHttpControllerRouteHandler(); } public class MyHttpControllerHandler: HttpControllerHandler, IRequiresSessionState { public MyHttpControllerHandler(RouteData routeData): base(routeData){ } } public class MyHttpControllerRouteHandler: HttpControllerRouteHandler { protected override IHttpHandler GetHttpHandler(RequestContext requestContext) { return new MyHttpControllerHandler(requestContext.RouteData); } } ``` Global.asax.cs ``` WebApiConfig.RegisterRoutes(RouteTable.Routes); ``` When I run this code I keep on getting null reference in the session. ``` HttpContext.Current.Session.Add("Username", user); //session["Username"] = user; //session.Add("Username", user); ``` Does anyone knows why I cannot set the session variable to anything. It does not matter which method I use non of the three are working. The code was taking from another post.