如何将自定义ModelValidatorProviders添加到Web API项目?

问题描述:

我正在将一些MVC代码移至Web API,并且需要更新自定义的ModelValidatorProviders.看来我的验证器可以保持几乎相同,只是它们应该继承System.Web.Http.Validation命名空间.

I'm moving some MVC code to Web API and I need to update my custom ModelValidatorProviders. It seems as though my validators can stay much the same only they should inherit the System.Web.Http.Validation namespace.

我不知道如何将提供程序添加到Web API.使用MVC时,我可以将以下内容添加到我的global.asax中:

What I can't figure out is how to add the provider to Web API. When using MVC I can just add the following to my global.asax:

ModelValidatorProviders.Providers.Add(new CustomModelValidatorProvider());

如何通过Web API使用自定义提供程序?

How do I use the custom provider with Web API?

此页面配置ASP.NET Web API 帮助我回答了自己的问题.具体来说,这就是我最终要做的事情:

This page Configuring ASP.NET Web API helped me answer my own question. Specifically this is what I ended up doing:

GlobalConfiguration.Configuration.Services.Add(typeof(ModelValidatorProvider), new CustomModelValidatorProvider());