Override Message “the value {0} is invalid for {1}” in case of int in WebAPI

我与影子孤独终老i 提交于 2020-01-04 06:11:42

问题


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.

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

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;

    }
}

And in my WebAPI.config :

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

Expected :

The value is not valid for CountryId.

Result :

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

回答1:


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}";
    }
}

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

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

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.




回答2:


I think this link will helps you, and Option #3: Use a custom model binder could be to the point solution.

public class LocationModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, 
      ModelBindingContext bindingContext)
    {
        string key = bindingContext.ModelName;
        ValueProviderResult val = bindingContext.ValueProvider.GetValue(key);
        if (val != null)
        {
            string s = val.AttemptedValue as string;
            if (s != null)
            {
                return Location.TryParse(s);
            }
        }
        return null;
    }
}

now we need to wire up the model binder.

   public object  MyAction2(
        [ModelBinder(typeof(LocationModelBinder))]
        Location loc) // Use model binding to convert
    {
        // use loc...
    }

https://blogs.msdn.microsoft.com/jmstall/2012/04/20/how-to-bind-to-custom-objects-in-action-signatures-in-mvcwebapi/




回答3:


Thanks Everyone! But I got the solution. To Overrride this message for Int Validation in WebAPI, you just need to add the following snippet in Application_Start method in Global.asax.cs

ModelBinderConfig.TypeConversionErrorMessageProvider = (context, metadata, value) => {

            if (!typeof(int?).IsAssignableFrom(value.GetType()))
            {
                return "The Value is not valid for " + metadata.PropertyName;
            }
            return null;
        };


来源:https://stackoverflow.com/questions/57591256/override-message-the-value-0-is-invalid-for-1-in-case-of-int-in-webapi

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