Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I let optional routing parameters allow null?

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?

like image 533
PardonMyCheckmate Avatar asked Mar 09 '26 19:03

PardonMyCheckmate


1 Answers

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
like image 165
Nkosi Avatar answered Mar 12 '26 09:03

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!