2013-03-03 67 views
2

環境調用Controller.Redirect或Controller.RedirectToAction:ASP.NET MVC 4時,Visual Studio 2012從外部庫

由MVC 4模板創建的AccountController包括RedirectToLocal程序,防止URL欺騙攻擊。我想把這個例程移到我自己的外部庫(在它自己的庫dll項目中)。經過一番調查,看起來最好的辦法是擴展Controller類。我的(不成功)嘗試這樣做如下所示。

我的問題是,Controller.Redirect和Controller.RedirectToAction都是受保護的內部函數,並且「由於其保護級別而無法訪問」。

什麼是從外部庫調用Redirect或RedirectToAction的常用方法?

public static class ControllerExtensionMethods 
{ 
    public static ActionResult RedirectToLocal(
            this Controller controller, 
            string redirectUrl) 
     { 
      if (controller.Url.IsLocalUrl(redirectUrl)) { 
       return controller.Redirect(redirectUrl); // error 
      } else { 
       return controller.RedirectToAction("Index", "Home"); // error 
      } 
     } 
} 

回答

2

我想解決這個就是製作並返回一個新的ActionResult,而不是試圖調用受保護的重定向程序的一種方式。我很感激來自知道這個東西比我更好的人的確認。

public static class ControllerExtensionMethods 
{ 
    public static ActionResult RedirectToLocal(
            this Controller controller, 
            string redirectUrl) 
     { 
      if (controller.Url.IsLocalUrl(redirectUrl)) { 
       return new RedirectResult(redirectUrl); 
      } else { 
       return new RedirectToRouteResult(
        new RouteValueDictionary { 
         {"controller", controllerName}, 
         {"action", actionName} 
        }); 
      } 
     } 
}