在Web Api 2中使用会话

时间:2015-05-06 15:30:18

标签: c# asp.net-web-api

我已经读过在web api 2中使用启用会话的有效方法是这样的:

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

我还创建了一个继承自AuthorizationFilterAttribute的类,并覆盖了OnAuthorization方法。

但这个事件从未被调用过 - 我做错了什么?

1 个答案:

答案 0 :(得分:0)

你可以尝试创建一个HttpModule:

public class WebApiSessionModule : IHttpModule
{
    protected virtual void OnPostAuthorizeRequest(object sender, EventArgs e)
    {
        HttpContext context = HttpContext.Current;

        if (this.IsWebApiRequest(context))
        {
            context.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.ReadOnly);
        }
    }
}

您需要将此添加到

中的web.config中
<system.web>
  <httpModules>