2010-03-18 135 views
50

使用ASP.Net MVC 2,有沒有什麼辦法在基於AuthorizeAttribute類的類中使用Controller類的RedirectToAction()方法?是否可以在自定義的AuthorizeAttribute類中使用RedirectToAction()?

public class CustomAttribute : AuthorizeAttribute { 
    protected override bool AuthorizeCore(HttpContextBase context) { 
     // Custom authentication goes here 
     return false; 
    } 

    public override void OnAuthorization(AuthorizationContext context) { 
     base.OnAuthorization(context); 

     // This would be my ideal result 
     context.Result = RedirectToAction("Action", "Controller"); 
    } 
} 

我正在尋找一種方式來重新將用戶引導到一個特定的控制器/行動時,他們失敗的驗證,而不是將其返回到登錄頁面。是否有可能爲該控制器/操作生成重定向URL,然後使用RedirectResult()?我試圖避免對網址進行硬編碼的誘惑。

回答

94

您可以/應該覆蓋HandleUnauthorizedRequest而不是OnAuthorization。下面是默認的實現:

protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext) { 
     // Returns HTTP 401 - see comment in HttpUnauthorizedResult.cs. 
     filterContext.Result = new HttpUnauthorizedResult(); 
    } 

不能使用Controller.RedirectToAction,但你可以返回RedirectToRouteResult

所以,你可以這樣做:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { 
     // Returns HTTP 401 - see comment in HttpUnauthorizedResult.cs. 
     filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary 
            { 
             { "action", "ActionName" }, 
             { "controller", "ControllerName" } 
            }); 
    } 
+1

謝謝,這是有效的。使用HandleUnauthorizedRequest的好處 - 我使用的是OnAuthorization,因爲我在另一個教程/討論中看到它(他們有一個自定義屬性,當認證失敗時會觸發重定向)。 – 2010-03-18 20:15:08

+0

@LanceMcNearney我會在參數filterContext中傳遞什麼? – Pomster 2013-07-12 09:51:18

+0

@Craig Stuntz我作爲filterContext傳入什麼? – Pomster 2013-07-12 09:53:26

11

你可以做這樣的事情:

var routeValues = new RouteValueDictionary(); 
routeValues["controller"] = "ControllerName"; 
routeValues["action"] = "ActionName"; 
//Other route values if needed. 
context.Result = new RedirectToRouteResult(routeValues); 

這是該框架做它,當你調用「RedirectToAction()」在你的控制器的方式。

+0

什麼是上下文?我有紅色的下劃線? – Pomster 2013-07-12 09:16:09

+0

@Pomster檢查問題,「上下文」是問題所關注的方法的一個參數。 – 2013-07-12 09:26:24

+0

謝謝,通過什麼來完成這項工作?我一直在努力獲得這個工作 – Pomster 2013-07-12 09:28:15

2

萬一別人很關心這個問題。 這可以通過更簡單的方式來解決(在使用MVC 3至少,不知道MVC 2):

只需創建您的自定義AuthorizeAttribute一個小型的私人控制器:

private class RedirectController : Controller 
    { 
     public ActionResult RedirectWhereever() 
     { 
      return RedirectToAction("Action", "Controller"); 
     } 

    } 

這很容易用於你的HandleUnauthorizedRequest方法(見Craigs答案):

filterContext.Result = (new RedirectController()).RedirectWhereever(); 
+2

'RedirectToAction'返回'RedirectToRouteResult',沒有必要創建一個控制器來返回一個,就像@Craig Stuntz的回答 – 2013-06-08 18:07:58

相關問題