Search code examples
c#.netasp.net-coreswagger

Can I customize error messages for values higher than allowed?


I want to set a custom messagem when a higher value than allowed is informed, at swagger. I have the following method in my controller:

public async Task<IActionResult> MyMethod(short someValue)

The max value for short in .Net is 32767, if I pass a higher value, I got the error message: "The value '999999' is not valid.", is there a way to customize that message?


Solution

  • It's a modelbinding error not model validation error,you may try set here:

    builder.Services.AddControllers(op => op.ModelBindingMessageProvider.SetNonPropertyAttemptedValueIsInvalidAccessor(input => input+" invalid")) ;
    

    Result:

    enter image description here

    For more detailed error message, you need to custom model binder,for example:

    public class MyBinder : IModelBinder
        {
            public Task BindModelAsync(ModelBindingContext bindingContext)
            {
                var modelName = bindingContext.ModelName;
    
                // Try to fetch the value of the argument by name
                var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
                if (valueProviderResult == ValueProviderResult.None)
                {
                    return Task.CompletedTask;
                }
    
                bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);
    
                var value = valueProviderResult.FirstValue;
    
                if (!short.TryParse(value, out var id))
                {
                    // add the logical compare the value and so on
                    bindingContext.ModelState.TryAddModelError(
                        modelName, value+" is not valid for short.");
    
                    return Task.CompletedTask;
                }
    
    
                return Task.CompletedTask;
            }
        }
    

    Apply the modelbinder :

    [ModelBinder(BinderType = typeof(MyBinder))] short someValue
    

    Result: enter image description here