2010-11-05 70 views

回答

15

你可以寫一個自定義action filter attribute

public class CustomFilterAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     // This method is executed before calling the action 
     // and here you have access to the route data: 
     var foo = filterContext.RouteData.Values["foo"]; 
     // TODO: use the foo route value to perform some action 

     base.OnActionExecuting(filterContext); 
    } 
} 

然後你可以用這個自定義屬性裝飾你的基本控制器。而這裏的一個blog post表示這種過濾器的一個樣本實現。

+1

在MVC3你沒有在主控制器:對全局過濾器支持(和MVC已經安裝了一個在'Global.asax.cs') 。 – Richard 2011-03-02 07:47:45

+0

@Richard,確保但我回答了這個問題MVC 3的時間尚未公佈:-)此外,它並沒有標記MVC 3 – 2011-03-02 07:51:55

+0

我知道 - 但它是* *現在真正的(我應該有加一個「現在」在那裏),記住SO是部分維基。 – Richard 2011-03-02 08:53:27

4

如果你想申請的每一個動作的文化,你可以創建一個基本的控制器,並覆蓋OnActionExecuting方法。

+0

這工作太出來。我猜它是在屬性同時被執行的。有趣的是它如何提供兩種選擇。 – 2010-11-05 07:34:30

1

如果你想過濾器添加到所有控制器,不只是選擇的搜索,你可以將它添加到「全局過濾器」。你在你的Global.asax.cs文件,這樣做在Application_Start()

protected void Application_Start() 
{ 
    AreaRegistration.RegisterAllAreas(); 

    // Register global filter 
    GlobalFilters.Filters.Add(new CustomFilterAttribute()); // ADDED 

    RegisterGlobalFilters(GlobalFilters.Filters); 
    RegisterRoutes(RouteTable.Routes); 
} 
相關問題