我遇到一个问题,就是每当我输入一个字符串请求 整数和布尔数据类型。由于NET CORE2.1的新功能“自动模型验证”,我收到了奇怪的错误消息。
这是请求
{
"EmailAddress" : "johndoe@gmail.com",
"EmailAddressConfirm" : "johndoe@gmail.com",
"FirstName" : "KL",
"MiddleName": "M",
"LastName" : "Lawingco",
"InquiryTypeID": "asda" ,
"InquiryContent" : "test",
"Validation" : true,
"TermsAndCondition" : false
}
它会抛出这样的错误
无法将字符串转换为整数:asda。路径“ InquiryTypeID”,第7行,位置26。
请注意,我也使用FluentValidation,但是从2.1开始,引入了自动模型验证。我的问题是,每当对int或boolean数据类型输入错误时,是否可以修改错误消息?
我尝试使用此功能关闭自动模型验证
services.Configure<ApiBehaviorOptions>(opt =>
{
opt.SuppressModelStateInvalidFilter = true;
});
但这也会杀死我的FluentValidation
这是我的模特
public class NewInquiry
{
public string EmailAddress{ get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string EmailAddressConfirm { get; set; }
public int? InquiryTypeID { get; set; }
public string InquiryContent { get; set; }
public bool Validation { get; set; }
public bool TermsAndCondition { get; set; }
}
希望你能帮助我,谢谢
答案 0 :(得分:0)
是的,您可以自定义/本地化所有模型输入的 ModelBinding 错误消息。
在启动文件中,您可以访问ModelBindingMessageProvider并设置所有模型绑定消息:
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddMvcOptions(o =>
{
o.ModelBindingMessageProvider.SetAttemptedValueIsInvalidAccessor((x, y) =>
string.Format("The value '{0}' is not valid for '{1}'", x, y));
o.ModelBindingMessageProvider.SetMissingBindRequiredValueAccessor((x) =>
string.Format("A value for the '{0}' property was not provided", x));
o.ModelBindingMessageProvider.SetMissingKeyOrValueAccessor(() =>
"A value is required");
o.ModelBindingMessageProvider.SetMissingRequestBodyRequiredValueAccessor(() =>
"A non-empty request body is required");
o.ModelBindingMessageProvider.SetNonPropertyAttemptedValueIsInvalidAccessor((x) =>
string.Format("The value '{0}' is not valid", x));
o.ModelBindingMessageProvider.SetNonPropertyUnknownValueIsInvalidAccessor(() =>
"The supplied value is invalid");
o.ModelBindingMessageProvider.SetNonPropertyValueMustBeANumberAccessor(() =>
"The field must be a number");
o.ModelBindingMessageProvider.SetUnknownValueIsInvalidAccessor((x) =>
string.Format("The supplied value is invalid for {0}", x));
o.ModelBindingMessageProvider.SetValueIsInvalidAccessor((x) =>
string.Format("The value '{0}' is invalid", x));
o.ModelBindingMessageProvider.SetValueMustBeANumberAccessor((x) =>
string.Format("The field '{0}' must be a number", x));
o.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor((x) =>
string.Format("The field '{0}' must not be null", x));
});
同样的方法也可以用于本地化