Sigurd Garshol
Sigurd Garshol

Reputation: 1544

Web API resolves parameters with mismatched types as missing

I am using ASP.NET Core to host a Web API. I have the following action defined in my Orders controller:

[HttpGet("list")]
public List<Order> List([FromQuery] int index = 0, [FromQuery] int length = 100)
{
    return GetOrders(index, length);
}

The following returns a single order:

https://localhost:5000/api/v1/Orders/list?index=0&length=1

The following returns 100 orders:

https://localhost:5000/api/v1/Orders/list?index=0&length=a

It appears that for a request, any parameters that cannot be converted to the declared type will be treated as missing, thus resulting in the use of the default value as per the example above, or the value type default value, or null for reference types.

In this case it is preferable to have the request fail when executed with mismatched parameter types rather than have it proceed with default/null values.

Is there a way to modify this behaviour?

Upvotes: 0

Views: 1465

Answers (1)

Alex Paven
Alex Paven

Reputation: 5549

This link is a comprehensive description of how model binding works in web api: https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Based on it, I'd say you'll need a custom model binder that throws an exception when it cannot convert the value.

Upvotes: 2

Related Questions