2009-08-26 16 views
7

我的ASP.NET MVC應用程序是一個更大的ColdFusion應用程序的一小部分,它將很快被完全替換。我通過Cookie傳遞ColdFusion部分的一些參數,並在運行每個操作之前需要檢查這些信息。如果信息丟失,我需要重定向到父站點。什麼是放置這個功能的最佳位置,以及如何正常調用它?如何在ASP.NET MVC中連接基本控制器的公共代碼

目前,我實現了一個基本的控制器,並在每個操作方法我調用基控制器的方法,並根據返回的結果要麼重定向或繼續行動。這種方法似乎可行,但它與我的行動方法混雜在一起,與行動無直接關係。我怎麼能把它分離出來,有沒有我可以使用的控制器的任何生命週期事件?

回答

6

如果你已經實現了一個基本的控制器只覆蓋其OnActionExecuting()方法:

public class YourBaseController : Controller 
{ 
    protected override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     base.OnActionExecuting(filterContext); 

     if(somethingIsWrong) 
     { 
      filterContext.Result = new RedirectToRouteResult(
       new System.Web.Routing.RouteValueDictionary { ... }); 
     } 
    } 
} 
2

如果這是需要在一個特定的控制器內的每一個動作,你很可能使用一個潛在的選擇是僅做到這一點基本控制器...

public class MyBaseController: Controller 
{ 
    protected override void Initialize(RequestContext requestContext) 
    { 
     base.Initialize(requestContext); 

     var cookie = base.Request.Cookies["coldfusioncookie"]; 
     //if something is wrong with cookie 
      Response.Redirect("http://mycoldfusionapp"); 
    } 
} 
2

更好的方法是實現自定義ActionFilterAttribute並覆蓋OnActionExecuting方法來處理邏輯,然後僅使用該屬性修飾您的操作。

public class CheckCookieAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     // Check your cookie and handle the redirect here, otherwise, do nothing 
     // You can get to your cookie through the filterContext parameter 
    } 
} 

public class ActionController : Controller 
{ 
    [CheckCookie] 
    public ActionResult GetFoo() 
    { 
     return View(); 
    } 
} 

希望這會有所幫助。

+1

Kurt的回答似乎更符合邏輯的,因爲這將在每一個動作進行。如果這只是某些行動,你的方法可能會更好。 – Martin 2009-08-27 02:04:00

+0

不用擔心馬丁。如果你需要每一個動作,那麼我會建議eu-ge-ne回答。我也是,但後來我看到了他的答案。 – 2009-08-27 12:12:04

相關問題