1

如果我有ApiController一个 post 方法,该方法使用具有用于验证的数据注释的模型,如何自定义为验证错误显示的名称?我真的不想覆盖整个错误消息,但我确实需要错误中的属性不是模型类型上的属性名称。

我已经尝试过 DisplayNameAttribute 和 DisplayAttribute 之类的东西,但这些似乎并不适用。

4

1 回答 1

1

我为此找到的最佳解决方案基于以下内容: https ://gist.github.com/benfoster/4016852

您必须创建自己的验证器提供程序(如链接所示),以及您自己的验证器,它将ValidationContext使用正确的 displayName 设置一个,这样

validationContext.DisplayName = displayNameMappingFunction(metadata.GetDisplayName());

然后,您需要使用 GlobalConfiguration.Services 全局注册验证器提供程序,或者您需要创建一个IControllerConfigurationAttribute仅为一个控制器配置它的验证器提供程序。

你做config.Services.Replace(typeof(ModelValidatorProvider), new CustomDisplayNameProvider()

于 2013-09-05T13:46:00.803 回答