我有一个变量名 CountryId(整数类型)。 如果用户向 CountryId 提供 string 或任何随机输入,ASP.Net 中的内置 DefaultBindingModel 会抛出错误:
The value '<script>gghghg</script>' is not valid for CountryId.
如果 ModelState 失败,我想覆盖此消息并提供我自己的文本。我想要一个通用的解决方案。
我搜索并尝试了很多解决方案,但它们只适用于 MVC 应用程序,不适用于 webAPI。
public class IntegerModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueProviderResult == null)
{
return base.BindModel(controllerContext, bindingContext);
}
int i;
return !int.TryParse(valueProviderResult.AttemptedValue.ToString(), out i) ? new ValidationResult("Failed") : ValidationResult.Success;
}
}
在我的 WebAPI.config 中:
ModelBinders.Binders.Add(typeof(int), new IntegerModelBinder());
预期:
The value is not valid for CountryId.
结果:
The value '<script>gghghg</script>' is not valid for CountryId.
请您参考如下方法:
网络应用程序接口(interface)
对于 Web API,您可以替换 TypeConversionErrorMessageProvider 以提供自定义消息。
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ModelBinderConfig.TypeConversionErrorMessageProvider = CustomTypeConversionErrorMessageProvider;
// rest of init code
}
private string CustomTypeConversionErrorMessageProvider(HttpActionContext actionContext, System.Web.Http.Metadata.ModelMetadata modelMetadata, object incomingValue)
{
return $"The value is not valid for {modelMetadata.PropertyName}";
}
}
注意 CustomTypeConversionErrorMessageProvider 的 modelMetadata 参数的完整限定;如果您不这样做,则会引用 System.Web.Mvc 的 ModelMetadata 类(由于 using 中的默认 code>Global.asax.cs),而不是 System.Web.Http.Metadata 中的那个,你会得到一个错误:-
Error CS0123 No overload for 'CustomTypeConversionErrorMessageProvider' matches delegate 'ModelBinderErrorMessageProvider'
MVC
对于 MVC,您可以使用 MVC 的本地化功能来替换那些验证消息。
基本上,您创建自己的资源文件,使用 DefaultModelBinder.ResourceClassKey 将 MVC 指向该资源文件,并在该资源文件中为 PropertyValueInvalid 键指定您自己的文本.
有关如何执行此操作的指南 here .
