2013-02-28 76 views
0

在Web API或ASP.NET MVC應用程序,我可以做加全球驗證過濾器 -驗證篩選特定的控制器

GlobalConfiguration.Configuration.Filters.Add(new ModelValidationFilterAttribute()); 

public class ModelValidationFilterAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(HttpActionContext actionContext) 
    { 
     if (actionContext.ModelState.IsValid == false) 
     { 
      actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState); 
     } 
    } 
} 

但我想有很多驗證適用於我選擇的控制器的過濾器?

回答

2

過濾器是可以應用於控制器或控制器中特定方法/動作的屬性。

要根據具體情況逐案使用過濾器,您可以執行下列操作之一:

[MyFilter] 
public class HomeController : Controller 
{ 
    //Filter will be applied to all methods in this controller 
} 

或者:

public class HomeController : Controller 
{ 
    [MyFilter] 
    public ViewResult Index() 
    { 
     //Filter will be applied to this specific action method 
    } 
} 

This tutorial詳細描述了過濾器,並提供了範例兩種情況。