如果WebAPI中为int,则覆盖消息“值{0}对{1}无效" [英] Override Message “the value {0} is invalid for {1}” in case of int in WebAPI

查看:105
本文介绍了如果WebAPI中为int,则覆盖消息“值{0}对{1}无效"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量名CountryId(整数类型). 如果用户向CountryId提供string或任何随机输入,则ASP.Net中的内置DefaultBindingModel会引发错误:

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.

如果ModelState失败,我想覆盖此消息并提供自己的文本.我想要一个通用的解决方案.

I want to override this message and provide my own text if the ModelState fails. I want a generic solution.

我已经搜索并尝试了许多解决方案,但是它们仅适用于MVC应用程序,不适用于webAPI.

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;

    }
}

在我的WebAPI.config中:

And in my WebAPI.config :

ModelBinders.Binders.Add(typeof(int),新的IntegerModelBinder());

ModelBinders.Binders.Add(typeof(int), new IntegerModelBinder());

预期:

该值对CountryId无效.

The value is not valid for CountryId.

结果:

The value '<script>gghghg</script>' is not valid for CountryId.

推荐答案

Web API

对于Web API,您可以替换TypeConversionErrorMessageProvider以提供自定义消息.

Web API

For Web API you can replace the TypeConversionErrorMessageProvider to provide a custom message.

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        ModelBinderConfig.TypeConversionErrorMessageProvider = CustomTypeConversionErrorMessageProvider;

        // rest of init code
    }

    private string CustomTypeConversionErrorMessageProvider(HttpActionContext actionContext, System.Web.Http.Metadata.ModelMetadata modelMetadata, object incomingValue)
    {
        return $"The value is not valid for {modelMetadata.PropertyName}";
    }
}

请注意CustomTypeConversionErrorMessageProvidermodelMetadata参数的完整限定;如果不执行此操作,则将引用System.Web.MvcModelMetadata类(由于Global.asax.cs中的默认using),而不是System.Web.Http.Metadata中的类,则会出现错误: -

Note the full qualification of the modelMetadata parameter of CustomTypeConversionErrorMessageProvider; if you don't do this, then the ModelMetadata class of System.Web.Mvc is referenced (due to the default usings in Global.asax.cs), instead of the one in System.Web.Http.Metadata, and you get an error:-

Error   CS0123  No overload for 'CustomTypeConversionErrorMessageProvider' matches delegate 'ModelBinderErrorMessageProvider'

MVC

对于MVC,您可以使用MVC的本地化功能替换那些验证消息.

MVC

For MVC, you can use the localization capability of MVC to replace those validation messages.

基本上,您创建自己的资源文件,使用DefaultModelBinder.ResourceClassKey将MVC指向该资源文件,然后在该资源文件中为PropertyValueInvalid键指定您自己的文本.

Basically, you create your own resource file, point MVC to that resource file using DefaultModelBinder.ResourceClassKey and in that resource file, specify your own text for the PropertyValueInvalid key.

有关如何执行此操作的指南

There is a guide on how to do this here.

这篇关于如果WebAPI中为int,则覆盖消息“值{0}对{1}无效"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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