ASP.NET WebApi Changing default parameter binding error message

╄→尐↘猪︶ㄣ 提交于 2020-01-14 04:03:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!