asp.net-mvc - 在 Controller 级别指定操作过滤器与在操作方法级别指定操作过滤器,后者将首先运行

标签 asp.net-mvc asp.net-mvc-4 asp.net-mvc-5 action-filter

当我创建一个 asp.net MVC 5 web 项目时,我检查了 Account Controller ,我找到了以下代码:-

 [Authorize]
    public class AccountController : Controller
    {
        public AccountController()
            : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
        {
        }
        // GET: /Account/Login
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

他们在 Controller 级别指定 [Authorize],在操作方法级别指定 [AllowAnonymous]。我认为 asp.net mvc 将首先检查 Controller 级别的所有 Action 过滤器,如果它们成功,它将使用 Action 方法调用进行处理。但似乎情况并非如此,因为匿名用户可以调用登录操作方法,尽管 [Authorize] 是在 Controller 级别指定的?那么这里的场景是什么?

谢谢

最佳答案

您可以先查看 Authorize 属性源代码以了解其工作原理:
http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/AuthorizeAttribute.cs

仔细查看 OnAuthorization 方法:您将看到它在操作或 Controller 上查找 AllowAnonymous 属性,如果找到,则跳过授权。

bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)
                                 || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);

if (skipAuthorization)
{
     return;
}

关于asp.net-mvc - 在 Controller 级别指定操作过滤器与在操作方法级别指定操作过滤器,后者将首先运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24309961/

相关文章:

c# - "Cannot support querying" Controller 错误

asp.net-mvc - 为什么 Razor View 在访问分配给局部变量的模型的索引器时向输入名称添加 "CS$<>8__locals1"前缀?

c# - MVC 中的 OnInit 和 Session

javascript - Angular JS $http POST 在 ASP.NET MVC 中成功时没有响应

c# - 如何在 Razor View 中检查模型字符串属性是否为 null

asp.net-mvc - 如何解决 JavaScriptSerializer 中超出 maxJsonLength 的异常?

c# - GlobalConfiguration.Configure() 在 Web API 2 和 .NET 4.5.1 迁移后不存在

c# - 在 MVC Controller 之外使用 Controller.Content c#

asp.net-mvc - 在 ASP.NET 4.5 和 VS 2012 RC 中将字符串发布到 Web API Controller

asp.net-mvc - 带有 ASP.NET MVC 的 Twitter Oauth,在哪里存储 secret token