在我们的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
{ …Run Code Online (Sandbox Code Playgroud)