1

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.

Community
  • 1
  • 1
Michal
  • 1,324
  • 2
  • 16
  • 38
  • You can create a custom ExceptionFilter to achieve your porpose. – Ankush Jain Nov 06 '14 at 12:58
  • @AnkushJain I have defined global exception filter but it is not reached in this case. I think I have to create some kind of custom binder or validator. – Michal Nov 06 '14 at 13:49
  • it will work. May be you have not followed proper rules to implement it. Read this carefully http://www.asp.net/web-api/overview/error-handling/web-api-global-error-handling – Ankush Jain Nov 06 '14 at 18:50

1 Answers1

1

Here is the solution:

// in Application_Start 
ModelBinderConfig.TypeConversionErrorMessageProvider = (context, metadata, value) =>
{
    ...
}
Michal
  • 1,324
  • 2
  • 16
  • 38