Reputation: 87
I'm trying to allow null values in one of my controller methods. It looks like this:
[Route("items/type/{catalogTypeId}/brand/{catalogBrandId}")]
public async Task<IActionResult> Items(int? catalogTypeId, int? catalogBrandId, [FromQuery] int pageSize = 6, [FromQuery] int pageIndex = 0)
When I try to postman items/type/1/brand/null?pageSize=6&pageIndex=0
it gives me an error 400
"The value 'null' is not valid".
How would I go with allowing the null value?
Upvotes: 3
Views: 2683
Reputation: 247098
Make route template parameter optional {catalogBrandId?}
[Route("items/type/{catalogTypeId}/brand/{catalogBrandId?}")]
public async Task<IActionResult> Items(int? catalogTypeId, int? catalogBrandId = null, [FromQuery] int pageSize = 6, [FromQuery] int pageIndex = 0)
and exclude it from URL
items/type/1/brand?pageSize=6&pageIndex=0
You should actually use multiple routes to get a cleaner URL
[Route("items")]
[Route("items/type/{catalogTypeId}")]
[Route("items/type/{catalogTypeId}/brand/{catalogBrandId}")]
public async Task<IActionResult> Items(int? catalogTypeId = null, int? catalogBrandId = null, [FromQuery] int pageSize = 6, [FromQuery] int pageIndex = 0)
Note the template is no longer optional but the parameter in the Action is optional.
This will allow
items?pageSize=6&pageIndex=0
items/type/1?pageSize=6&pageIndex=0
items/type/1/brand/2?pageSize=6&pageIndex=0
Upvotes: 5