我有 4 个控制器,即Account
、和。在这 4 个控制器中,我只需要授权控制器,其余的可以匿名访问。所以我用属性装饰了我的家庭控制器、画廊控制器和帐户控制器,并且我用我的自定义授权过滤器装饰了我的控制器,它包含以下代码。Admin
Home
Gallery
Admin
[AllowAnonymous]
Admin
[CustAuthFilter]
public class CustAuthFilter : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var request = httpContext.Request;
string controller = request.RequestContext.RouteData.Values["controller"].ToString().ToLower();
if (controller != "" && controller == "admin")
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
return false;
}
else
{
if (!object.ReferenceEquals(httpContext.Session["un"], null))
{
return true;
}
else
{
return false;
}
}
}
else
{
return true;
}
}
override public void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext.Result is HttpUnauthorizedResult && filterContext.HttpContext.Request.IsAjaxRequest())
{
String url = System.Web.Security.FormsAuthentication.LoginUrl + "?X-Requested-With=XMLHttpRequest";
filterContext.Result = new RedirectResult(url);
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
String url = System.Web.Security.FormsAuthentication.LoginUrl;
filterContext.Result = new RedirectResult(url);
}
}
在我的 web.config 中,我关注
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" defaultUrl="~/Admin/Index" timeout="2880" protection="Encryption" slidingExpiration="true" cookieless="AutoDetect"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
我已经在过滤器中注册了我的自定义授权属性,如下所示:
filters.Add(new CustAuthFilter());
但是每当我尝试访问时domainname/home
,domainname/gallery
它都会自动重定向到domainname/account/login
. 但我不知道为什么即使在用[AllowAnonymous]
它装饰家庭和画廊控制器之后也会重定向到帐户控制器!