'MaxLength decorator is not working with int.MaxValue

Given this basic GET method:

public Foo Get([FromQuery][MaxLength(int.MaxValue, ErrorMessage ="Custom error message")] int input)
{
   // DO THINGS
}

The MaxLength decorator is not working when I actually send a value bigger than int.MaxValue:

https://apiurl/foo?input=9999999999999999999

I get a System.OverflowException: 'Value was either too large or too small for an Int32.', way before it reaches the MaxLength validator, in System.Private.CoreLib

Is there an easy way to handle this error and actually return my custom Error Message or do I have to implement a custom ModelBinder?



Solution 1:[1]

Create an custom attribute:

public class CustomNameAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext context)
    {
        if (context.Result is BadRequestObjectResult badRequestObjectResult)
            if (badRequestObjectResult.Value is ValidationProblemDetails)
            {
                context.Result = new BadRequestObjectResult("Error message");
            }
        base.OnResultExecuting(context);
    }
}

Then add it to your method:

[CustomName]
public Foo Get([FromQuery]int input)
{
   // DO THINGS
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mateech