2013-04-22 37 views
1

淨MVC4我使用一個子類AuthorizeAttribute重定向到「更改密碼」頁面上的所有請求,當用戶的密碼已重置爲:如何在.Net MVC4中實現「更改密碼」重定向?

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

您的實現看起來不錯。但是如果你想要簡單,你可以使用標準的'[Authorize]'屬性,並在web.config文件中設置重定向目標 – 2013-04-23 01:41:43

回答

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