I have a variable name CountryId
(Integer Type).
If user provides a string
or any random input to CountryId
, the In-built DefaultBindingModel
in ASP.Net throws an error :
The value '<script>gghghg</script>' is not valid for CountryId.
I want to override this message and provide my own text if the ModelState
fails. I want a generic solution.
I've searched and tried many solutions, but they only worked for MVC applications, not 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;
}
}
And in my WebAPI.config :
ModelBinders.Binders.Add(typeof(int), new IntegerModelBinder());
Expected :
The value is not valid for CountryId.
Result :
The value '<script>gghghg</script>' is not valid for CountryId.