本文介绍了Web Api 2 HttpContext或HttpActionContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下两种通过AuthorizeAttribute
实现访问原理的方式之间有什么区别?
What is the difference between the following two ways of accessing the principle via an AuthorizeAttribute
implementation?
使用HttpContext
:
Using HttpContext
:
protected override bool IsAuthorized(HttpActionContext actionContext)
{
return HttpContext.Current.User.IsInRole("DemoRole");
}
使用HttpActionContext
:
Using HttpActionContext
:
protected override bool IsAuthorized(HttpActionContext actionContext)
{
return actionContext.RequestContext.Principal.IsInRole("DemoRole");
}
推荐答案
它们是相同的,您可以通过在方法中包括以下行来证明这一点:
They are the same, which you can prove by including this line in the method:
Debug.Assert(actionContext.RequestContext.Principal == HttpContext.Current.User);
我个人会使用actionContext
,因为使用HttpContext.Current
会创建一个依赖项,并且使它变得更难例如单元测试.
I would personally use the actionContext
, since using HttpContext.Current
creates a dependency, and makes it harder to e.g. unit test.
这篇关于Web Api 2 HttpContext或HttpActionContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!