2010-05-28 69 views
0

我剛剛在ASP.net 4.0開始了一個新項目,MVC 2如何定製掛鉤添加到控制器中的ASP.NET MVC2

我需要什麼,能夠做的是有一個自定義勾控制器每個動作的開始和結束。

例如

public void Index() { 
    *** call to the start custom hook to externalfile.cs (is empty so does nothing) 

    ViewData["welcomeMessage"] = "Hello World"; 

    *** call to the end custom hook to externalfile.cs (changes "Hello World!" to "Hi World") 

    return View(); 
} 

該視圖然後在自定義掛鉤中更改後將welcomeMessage視爲「Hi World」。

自定義鉤子需要在外部文件中,而不是更改「核心」編譯代碼。這導致一個問題,因爲我有限的知識ASP.net MVC必須編譯。

有沒有人對此有何建議?

感謝

回答

3

您可以根據ActionFilterAttribute創建自己的班級。它有以下幾個鉤子。

  1. OnActionExecuted
  2. OnActionExecuting
  3. OnResultExecuted
  4. OnResultExecuting

例如,

public class MyFilterAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
     var controller = filterContext.Controller; 

     controller.ViewData["welcomeMessage"] = "Hi World!"; 
     controller.TempData["Access_My_TempData"] = "Some Value"; 

     base.OnActionExecuted(filterContext); 
    } 
} 

您還可以檢查操作方法是什麼類型的[動作]執行。

if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult)) 
{ 
    // do something only if we are redirecting to a different action 
} 
else if (filterContext.Result is ViewResult) 
{ 
    // this is just a normal View action 
} 

哦,我忘了說明如何使用該屬性。
你只是在你的動作方法上進行裝飾。

[MyFilterAttribute] 
public ActionResult MyActionMethod() 
{ 
    return View(); 
} 
+0

如果您不想手動將屬性放在每個操作上,我相信您可以創建一個通用的基本控制器類型並將該屬性放在類型本身上。 – Ryan 2010-05-28 20:00:23

+0

這看起來像我希望做的事情。 謝謝 – Adrian 2010-06-07 10:39:29

1

一個基於事件的插件系統,您可以動態調用腳本代碼。因此,創建(例如)控制器引發事件時調用的鐵python腳本。

不一定是鐵蟒,但那會使我能看到的最有意義。

+0

我已經做了類似的,儘管不是在MVC。 運作良好。 – 2010-05-28 10:26:37

0

如何重寫OnActionExecuting/OnActionExecuted並使用MEF(導入,導出其他彙編代碼)?

+0

爲什麼在這個概念已經在MVC框架中使用MEF作爲ActionFilter? – Ryan 2010-05-28 20:01:26

+0

因爲它認爲執行了動作過濾器中的動態注入代碼。 – takepara 2010-05-28 23:32:17