问题
I have action method defined as
public HttpResponseMessage Get(SomeEnum? param)
{
...
}
If I pass some invalid value for param which is not convertible to Some Enum type I get this message:
The value 'xxx' is not valid for Nullable`1.
It is default message which I can get from ModelState. I would like to customize this message. I have found plenty of tips how to do it in ASP.NET MVC (like here) but nothing for WebAPI. Changing DefaultModelBinder.ResourceClassKey does not work in WebAPI. I have also tried to solve problem by customizing ParameterBindingRule:
config.ParameterBindingRules.Insert(0, parameter =>
{
if (!typeof (EnumType?).IsAssignableFrom(parameter.ParameterType))
return parameter.BindAsError("Error message");
return null;
});
Unfortunately this also doesn't work.
回答1:
Here is the solution:
// in Application_Start
ModelBinderConfig.TypeConversionErrorMessageProvider = (context, metadata, value) =>
{
...
}
来源:https://stackoverflow.com/questions/26779938/asp-net-webapi-changing-default-parameter-binding-error-message