代码之家  ›  专栏  ›  技术社区  ›  Paul Fryer

ASP.NET MVC控制器属性在操作之前或之后执行吗?

  •  2
  • Paul Fryer  · 技术社区  · 15 年前

    请考虑以下代码:

        [Authenticate(Order = 1)]
        public ActionResult SomeActionThatRequiresAuthentication()
        { 
            var model = new SomeViewModel(); 
            // Do something with an authenticated session/user...
            return View(model);
        }
    

    Authenticate 属性发生在 SomeActionThatRequiresAuthentication 方法是否已执行?

    我这样问是因为我有这样的属性:

        public class Authenticate : CustomAuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!UserService.IsAuthenticated && !HttpContext.Current.Response.IsRequestBeingRedirected)
                HttpContext.Current.Response.Redirect(ViewUtil.Actions.User.LogOnUrl());
        }
    }
    

    如您所见,如果用户未通过身份验证,该属性将重定向用户。但是,似乎重定向只在操作执行之后发生。这导致了问题,因为我假设用户在执行操作时经过了身份验证。首先,我需要了解属性是应该在执行操作之前还是之后发生,还是我认为工作流完全错误?

    谢谢,保罗


    在进一步研究之后,很明显 filterContext.Result 必须为此设置才能工作。在我的authorize属性中做了一个小的更改之后,它现在开始工作:

        public class Authenticate : CustomAuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!UserService.IsAuthenticated && !HttpContext.Current.Response.IsRequestBeingRedirected)
                filterContext.Result = new RedirectResult(ViewUtil.Actions.User.LogOnUrl());
        }
    }
    
    1 回复  |  直到 13 年前
        1
  •  4
  •   Brandon Satrom    15 年前

    你是对的,属性执行 之前 有问题的行动,所以 [Authenticate] 应该首先执行,如果用户没有经过身份验证,那么在用户被重定向、身份验证并被重定向回此操作之前,操作代码永远不会执行。

    基于注释编辑 :MVC框架 OnAuthorizatrion 方法(来源) here )不重定向,但将filterContext.result设置为“httpUnauthorizedResult()”(仅设置401状态代码)。这将导致身份验证模块将用户重定向到登录页面。假设自定义实现的其余部分是标准的(不是重写或调用基方法),更改此

    HttpContext.Current.Response.Redirect(ViewUtil.Actions.User.LogOnUrl()); 
    

    为此(或类似的事情,只要设置结果)

    filterContext.Result = new HttpUnauthorizedResult();
    

    应该做的技巧,至少让你走的更远。