ASP.net MVC 全局授权过滤器在 AllowAnonymous 动作上强制登录

9 浏览
0 Comments

ASP.net MVC 全局授权过滤器在 AllowAnonymous 动作上强制登录

设置(使用MVC 4)

public class MyAuthorizeAttribute : AuthorizeAttribute {
    protected override bool AuthorizeCore(HttpContextBase httpContext) {
        var isAuthorised = base.AuthorizeCore(httpContext);
        if(isAuthorised) {
            // 从cookie中检索身份验证票证,并创建自定义主体并附加到httpContext.User
        }
        return isAuthorised;
    }
}

Gloabl.asax.cs:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new MyAuthorizeAttribute());
}

HomeController.cs:

using System.Web.Mvc;
public class HomeController : Controller
{
    [AllowAnonymous]
    public ActionResult Index()
    {
        return View();
    }
}

问题

访问主页时会强制加载登录页面。

问题

当HomeController.Index()操作使用[AllowAnonymous]修饰时,为什么ASP会重定向我到登录视图?

我参考了这篇文章。

0
0 Comments

问题的出现原因:在web.config文件中,存在一个标签,并设置了,这将导致在没有登录的情况下无法执行任何操作,除非是登录操作。

解决方法:将标签中的移除或注释掉。

0
0 Comments

我遇到了类似的问题,最后发现我使用了错误的AllowAnonymousAttribute类。有两个AllowAnonymousAttribute类:

在你的情况下,你当然要使用System.Web.Mvc的那个:)

我花了一个多小时才找出这个问题。

0
0 Comments

问题的原因是在index视图中调用了其他控制器返回的部分视图,解决方法是去掉旧的[Authorize]属性。

0