简体   繁体   中英

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM