Web Api 2 HttpContext或HttpActionContext

Dav*_*New 7 owin katana asp.net-web-api2

以下两种通过AuthorizeAttribute实现访问原理的方法有什么区别?

使用HttpContext:

protected override bool IsAuthorized(HttpActionContext actionContext)
{
    return HttpContext.Current.User.IsInRole("DemoRole");
}
Run Code Online (Sandbox Code Playgroud)

使用HttpActionContext:

protected override bool IsAuthorized(HttpActionContext actionContext)
{
    return actionContext.RequestContext.Principal.IsInRole("DemoRole");
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*vén 4

它们是相同的,您可以通过在方法中包含这一行来证明:

Debug.Assert(actionContext.RequestContext.Principal == HttpContext.Current.User);
Run Code Online (Sandbox Code Playgroud)

我个人会使用actionContext,因为使用HttpContext.Current会创建依赖关系,并使单元测试变得更困难。