ASP.NET Core model binding and integers

Viewed 1461

Having this in my Controller

[HttpGet]
public string Get([FromQuery] QueryObject obj)
{
    return "value";
}

public class QueryObject
{
    public int Number { get; set; }
}

When I invoke the Get Method with this URL

http://localhost/MyController?Number=HELLO

I end up having a QueryObject instance with Number = 0

Why this ever happens? The query is clearly a BAD REQUEST, since Number is a integer and the query has a string.

1 Answers

The model binding will try to parse the request and bind to the properties of your object. If it's invalid, then you'll find an error in the ModelState object.

e.g.

        if (!ModelState.IsValid)
        {
            // The ModelState is a Dictionary
            // holding details of the model binding errors
        }

For more info: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation

Related