ASP.NET WebApi更改默认参数绑定错误消息 [英] ASP.NET WebApi Changing default parameter binding error message

查看:216
本文介绍了ASP.NET WebApi更改默认参数绑定错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将动作方法定义为

public HttpResponseMessage Get(SomeEnum? param)
{
   ...
}

如果我为param传递了一些无效的值,该值不能转换为Some Enum类型,则会收到此消息:

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.

这是我可以从ModelState获得的默认消息.我想自定义此消息.我发现了很多在ASP.NET MVC中执行操作的技巧(例如

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.

推荐答案

以下是解决方法:

// in Application_Start 
ModelBinderConfig.TypeConversionErrorMessageProvider = (context, metadata, value) =>
{
    ...
}

这篇关于ASP.NET WebApi更改默认参数绑定错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆