问题
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:
- Why values in the
Session
are not available in theAuthenticationFilter
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 fromSession
in theAuthenticationFilter
only. ! - I know that using Session is not recommended but at present I have to live with it.
SessionStateBehavior
is set already toRequired
for the Web Api using following event in theGlobal.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