【发布时间】:2019-12-26 17:03:33
【问题描述】:
我有一个变量名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());
预期:
该值对 CountryId 无效。
结果:
The value '<script>gghghg</script>' is not valid for CountryId.
【问题讨论】:
-
在这种情况下不要使用DefaultBindinModel,也请在问题中输入一些代码
-
@PrasadTelkikar 我知道消息更清楚,但要求是 EndUser 应该不能看到输入值。
-
@CodeNameJack 我尝试制作自己的 BinderModel,但它不起作用。我正在制作资源文件并添加了一个字段“PropertyValueInvalid The value '{0}' is not valid for {1}.”。但没有运气。
标签: c# asp.net-web-api model-binding