WebAPI 2 attribute routing enable session state

♀尐吖头ヾ 提交于 2019-12-18 15:44:10

问题


We figured out how to enable session state with webapi Sample here

Now we have WebApi 2 attribute routing, so we no longer have route object to inject custom handler.

Is there any way of enabling session state with attribute routing?


回答1:


You need to add this to global.asax

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

Then you could access the session through:

HttpContext.Current.Session



回答2:


in the global.asax

Private Sub WebApiApplication_PostAuthorizeRequest(sender As Object, e As EventArgs) Handles Me.PostAuthorizeRequest
     System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required)
End Sub



回答3:


You can use the SessionStateUtility class to get the session state. Just call:

var session = SessionStateUtility.GetHttpSessionStateFromContext(HttpContext.Current)

Api controllers are designed for restful services and should generally be stateless. Not loading the session every time is one of the things that makes them lighter weight.



来源:https://stackoverflow.com/questions/19758221/webapi-2-attribute-routing-enable-session-state

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