【发布时间】:2015-10-22 18:45:50
【问题描述】:
在我们的 asp.net mvc/web api 项目中,我们希望使用AuthorizeAttribute 自定义授权。我们注意到有两种不同的AuthorizeAttribute,一种在System.Web.MVC 命名空间中用于MVC,另一种在System.Net.Http 命名空间中用于Web api。
它在MVC中工作,我们的代码是这样的:
public class MyPrincipal : IPrincipal
{
//some custom properties
public bool IsValid()
{
//custom authentication logic
}
private IIdentity identity;
public IIdentity Identity
{
get { return this.identity; }
}
public bool IsInRole(string role)
{
return true;
}
}
//override AuthorizeCore
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
MyPrincipal user = new MyPrincipal();
if (user.isValid())
{
httpContext.User = user;
}
else
{
httpContext.Response.Redirect("~/Common/NoAuthorize", true);
}
}
}
[MyAuthorizeAttribute]
public class BaseMyController : Controller
{
protected virtual new MyPrincipal User
{
get { return HttpContext.User as MyPrincipal; }
}
}
然后在MVC控制器中,我们可以通过MyPrincipal用户属性获取用户信息。
但是,当我们开始在web api中使用相同的方式时,我们发现web api没有HttpContext属性,并且在System.Web.Http.AuthorizeAttribute中,被覆盖的方法接受HttpActionContext参数,它也有没有HttpContext 属性或其他我们可以设置MyPrincipal 实例的地方。
我注意到System.Web.Http.AuthorizeAttribute 总结说
指定验证请求的 IPrincipal 的授权过滤器
似乎还有其他方法可以设置IPrincipal 实例。
我不知道,有什么好的建议吗?对了,为什么asp.net web api控制器没有HttpContext?有没有关于它的设计模式?
【问题讨论】:
标签: asp.net-mvc asp.net-web-api