.NET Web API + Session Timeout

冷暖自知 提交于 2020-01-24 12:59:30

问题


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.


回答1:


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);
}



回答2:


This is where semantics often clouds the discussion. People confuse the Session object with statelessness. And often say: 'don't use session because it isn't stateless!'.

However they really mean that you should strive to have your the restful calls to be idempotent, meaning they don't change their behavior depending on whatever it is you do in the background.

Session, or the runtime-cache, or whatever it is you use to cache data, has no effect on your stateless design, because really, what's next? Your database is statefull too? And you shouldn't read data from that? Nonsense obviously; your underlying storage, if it's in-memory or on disk has no reflection on your state to the client.

So use, by all means, the session object as Ben Robinson pointed out. But never let the fact if something is IN session return a different result then when something is OUT of session.




回答3:


Please, don't!

Web API is supposed to be stateless, RESTful, etc. By using State you're defeating its whole purpose.



来源:https://stackoverflow.com/questions/27275974/net-web-api-session-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!