Missing values in the HttpContext Session when accessed in the WebApi 2.0 custom Authentication Filter

怎甘沉沦 提交于 2019-12-25 13:44:50

问题


In my web services (WebApi 2.0), I have implemented IAuthenticationFilter which checks some values in the HttpContext.Current.Session (E.g. HttpContext.Current.Session["TokenId"]) and decides whether user is authorized to proceed or not. I have registered this filter in the FilterConfig class like following so that this filter is executed everytime anybody is calling Web Api.

config.Filters.Add(new WebApiAuthenticationFilter());

My MVC 4 application has a custom AuthorizeAttribute. This attribute is executed for every controller action. This attribute internally calls my Web Api. When Web Api is called, the authentication filter automatically gets executed which tells user is authorized or not. This is how I come to know about user's authorization status in my MVC application.

I observed that HttpContext.Current.Session["TokenId"] returns null only for the first Web Api call. Then onwards, I get correct value in the HttpContext.Current.Session["TokenId"].

Questions:

  1. Why values in the Session are not available in the AuthenticationFilter during first Web Api call only?

Note:

  • My Web Api and MVC code runs in the same web application.
  • HttpContext.Current.Session is NOT null. Only data (like TokenId) stored in Session is not available.
  • Same TokenId is available if I access Session from my MVC custom authorization attribute or inside actual Web Api controller if I let the call proceed upto Web Api controller. The value is missing from Session in the AuthenticationFilter only. !
  • I know that using Session is not recommended but at present I have to live with it.
  • SessionStateBehavior is set already to Required for the Web Api using following event in the Global.asax file.

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

来源:https://stackoverflow.com/questions/31716450/missing-values-in-the-httpcontext-session-when-accessed-in-the-webapi-2-0-custom

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