在控制器级别指定操作筛选器与操作方法级别指定操作筛选器将首先运行

时间:2014-06-19 15:08:03

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

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

 [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();
        }

在控制器级别指定[Authorize],在action方法级别指定[AllowAnonymous]。我认为asp.net mvc将首先检查控制器级别的所有动作过滤器,如果它们成功,它将使用action方法调用进行处理。但似乎这不是情况,因为匿名用户可以调用登录操作方法,虽然在控制器级别指定了[Authorize]?那么这里的情景是什么?

由于

1 个答案:

答案 0 :(得分:3)

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

仔细查看OnAuthorization方法:您将看到它在操作或控制器上查找AllowAnonymous属性,并在找到任何属性时跳过授权。

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

if (skipAuthorization)
{
     return;
}
相关问题