2011-01-25 30 views
18

我想知道如何在控制器構造函數中重定向請求,如果我需要這樣做?MVC - 構造函數內部的重定向

例如: 在構造函數中,我需要用動態值初始化一個對象,在某些情況下,我不想這樣做,在這種情況下我想重定向到其他某個地方。 以同樣的方式,構造函數的其餘部分不會被執行,也不會執行「原始的下一個動作」。

我該怎麼辦? 謝謝

編輯#1

起初我用:

public override void OnActionExecuting(ActionExecutingContext filterContext) 

在那裏,我可以重定向到其他一些控制器/動作/ URL,但後來的時候,我需要改變我控制器,其中我在他的構造函數初始化一個變量,並有一些代碼,真的需要重定向請求:P

我需要這也是因爲OnActionExecuting執行AFTER th e控制器構造函數。 在我的邏輯中,重定向需要在那裏完成。

回答

45

在控制器構造函數內部執行重定向並不是一種好的做法,因爲上下文可能未被初始化。標準做法是編寫自定義操作屬性並覆蓋OnActionExecuting方法並在其中執行重定向。例如:

public class RedirectingActionAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     base.OnActionExecuting(filterContext); 

     if (someConditionIsMet) 
     { 
      filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new 
      { 
       controller = "someOther", 
       action = "someAction" 
      })); 
     } 
    } 
} 

然後裝飾您想用此屬性重定向的控制器。要特別小心,不要裝飾你用這個屬性重定向到的控制器,否則你將會遇到無限循環。

所以,你可以:

[RedirectingAction] 
public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     // This action is never going to execute if the 
     // redirecting condition is met 
     return View(); 
    } 
} 

public class SomeOtherController : Controller 
{ 
    public ActionResult SomeAction() 
    { 
     return View(); 
    } 
} 
+0

你打我吧:)。 – bastijn 2011-01-25 12:29:33