WebAPI 2 attribute routing enable session state

2019-02-08 19:34发布

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?

3条回答
太酷不给撩
2楼-- · 2019-02-08 19:56

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.

查看更多
小情绪 Triste *
3楼-- · 2019-02-08 19:59

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
查看更多
聊天终结者
4楼-- · 2019-02-08 20:04

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
查看更多
登录 后发表回答