回答

16

的follwing類允許這樣做有FilterProvider

public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) 
{ 
    List<Filter> result = new List<Filter>(); 

    string incomingVerb = controllerContext.HttpContext.Request.HttpMethod; 

    if (String.Equals(incomingVerb, "POST", StringComparison.OrdinalIgnoreCase)) 
    { 
     result.Add(new Filter(new ValidateAntiForgeryTokenAttribute(), FilterScope.Global, null)); 
    } 

    return result; 
} 

使用上述類global.asx文件將其添加到RegisterGlobalFilters方法:

...  
FilterProviders.Providers.Add(new AntiForgeryTokenFilterProvider()); 
.. 

這樣做,每個[HttpPost]將檢查如果Html.AntiForgeryToken()在視圖中。

+1

您的過濾器提供程序是否繼承自任何基類? – Paul 2011-06-15 03:00:22

+5

該代碼將爲應用程序的每個請求創建一個列表。它可以通過使用yield來改進:yield return new Filter(new ValidateAntiForgeryTokenAttribute(),FilterScope.Global,null); – ShadowChaser 2012-06-30 20:28:47

+1

鏈接到完整的類爲clarities清酒:https://code.google.com/p/vnecoo/source/browse/trunk/Code/Oas2011/OAS/Helpers/AntiForgeryTokenFilterProvider.cs?r=148 – Jon 2013-11-07 10:41:21