Reputation: 1822
In a Web API or ASP.NET MVC application I can add a Global validation filter by doing -
GlobalConfiguration.Configuration.Filters.Add(new ModelValidationFilterAttribute());
and
public class ModelValidationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
But I want to have many validations filters that apply to controllers of my choice?
Upvotes: 0
Views: 2383
Reputation: 5785
Filters are attributes that can be applied to your controllers or specific methods/actions in your controllers.
To use your filter on a case-by-case basis, you can do either of the following:
[MyFilter]
public class HomeController : Controller
{
//Filter will be applied to all methods in this controller
}
Or:
public class HomeController : Controller
{
[MyFilter]
public ViewResult Index()
{
//Filter will be applied to this specific action method
}
}
This tutorial describes filters in detail and provides examples of both scenarios.
Upvotes: 2