如何让可选的路由参数允许为空?

How do I let optional routing parameters allow null?

我试图在我的控制器方法之一中允许空值。 它看起来像这样:

[Route("items/type/{catalogTypeId}/brand/{catalogBrandId}")]
public async Task<IActionResult> Items(int? catalogTypeId, int? catalogBrandId, [FromQuery] int pageSize = 6, [FromQuery] int pageIndex = 0)

当我尝试发送邮递员 items/type/1/brand/null?pageSize=6&pageIndex=0 时,它给我一个错误 400

"The value 'null' is not valid".

我将如何允许空值?

使路由模板参数可选{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)

并将其从 URL

中排除
items/type/1/brand?pageSize=6&pageIndex=0

你实际上应该使用多条路线来获得清洁剂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)

请注意,模板不再是可选的,但操作中的参数是可选的。

这将允许

items?pageSize=6&pageIndex=0
items/type/1?pageSize=6&pageIndex=0
items/type/1/brand/2?pageSize=6&pageIndex=0