如何在.Net MVC4中实现“更改密码”重定向?

时间:2013-04-22 15:13:18

标签: redirect asp.net-mvc-4 filter authorization t4mvc

.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调用吗?

感谢任何指针...

1 个答案:

答案 0 :(得分: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 }
                });
        }
    }
}