gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:01:24 24 4
gpt4 key购买 nike

我试图在我的一个 Controller 方法中允许空值。它看起来像这样:

[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

关于c# - 如何让可选的路由参数允许为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55496515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com