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);
        }
    } 
}

但我想要有许多适用于我选择的控制器的验证过滤器?

4

1 回答 1

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
    }
}

本教程详细描述了过滤器并提供了两种方案的示例。

于 2013-02-28T20:07:26.380 回答