1

.Net MVC4中,当用户的密码被重置时,我使用子类AuthorizeAttribute将所有请求重定向到“更改密码”页面,如下所示:

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // Call base class method first
        base.OnAuthorization(filterContext);

        // Only redirect if password change is required and the requested action
        // is not "Change Password"
        if (!passwordChangeRequired
            && !(filterContext.Controller is ApplicantController &&
                 MVC.Applicant.ActionNames.ChangePassword.Equals(filterContext.ActionDescriptor.ActionName)))
        {
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary
                {
                    { "controller", MVC.Applicant.Name },
                    { "action", MVC.Applicant.ActionNames.ChangePassword }
                });
        }
    }

刚刚编写了这段代码,它似乎可以工作,但还没有信心,想知道它是否可以简化。

特别是关于控制器和动作 - 项目使用T4MVC,所以两者都需要单独包含在检查和重定向中,还是可以以某种方式组合?

也应该base.OnAuthorization在开始或结束(或两者都不)进行呼叫?

感谢任何指针...

4

1 回答 1

3

我最终对此稍作修改以使用ActionFilterAttribute而不是AuthorizeAttribute

如果这对任何人有用,这里是代码:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class ChangePasswordAttribute : ActionFilterAttribute
{
    /// <summary>
    /// Filter on executing
    /// </summary>
    /// <param name="filterContext">The current action context</param>
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        // Don't redirect to "Change Password" action if it is the current action
        if (filterContext.Controller is ApplicantController &&
            MVC.Applicant.ActionNames.ChangePassword.Equals(filterContext.ActionDescriptor.ActionName))
        {
            return;
        }

        // Redirect if password change is required
        if ((filterContext.HttpContext.Session[SessionKeys.PasswordChangeRequired] != null) 
            && (bool)filterContext.HttpContext.Session[SessionKeys.PasswordChangeRequired])
        {
            // Save route in session so the user can be redirected appropriately after a successful password change
            RouteValueDictionary routeValues = new RouteValueDictionary(filterContext.RouteData.Values);
            filterContext.HttpContext.Session[SessionKeys.PasswordChangeRouteValues] = routeValues;

            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary
                {
                    { "controller", MVC.Applicant.Name },
                    { "action", MVC.Applicant.ActionNames.ChangePassword }
                });
        }
    }
}
于 2013-04-23T11:30:27.423 回答