【发布时间】:2019-12-15 14:56:54
【问题描述】:
阅读使用ApiControllerAttribute 的所有优点,但是,如果我们希望在使用此属性作为查询参数时具有可选参数,则它不起作用。它仍然将所有参数验证为强制参数。知道如何使它成为可选的吗?
[ApiController]
public class testController: ControllerBase
{
[HttpGet("employees/{id?}")]
public List<Employees> GetAll(int? id)
{
// gets all employees or by id
}
}
当这段代码被执行时,它一直期待id。没有这个参数就不会运行。
编辑:即使传递了 id 的默认值,它也不起作用。
【问题讨论】:
-
添加默认值
[HttpGet("employees/{id?}")] public List<Employees> GetAll(int? id = null) -
好吧,试过了,它仍然说“值'null'无效”400错误。这是因为 ApiController 进行了验证。如果我删除它,它工作正常。我只是想知道,如何使它与 ApiController 属性一起工作。
-
也许这里的文档可能有助于理解 ApiController docs.microsoft.com/en-us/aspnet/core/web-api
-
您的 .net 核心版本是什么?我用
netcoreapp2.2进行了测试,它与[HttpGet("employees/{id?}")]一起正常工作。与我们分享一个可以重现您的问题的迷你演示。 -
原来这是一个招摇的问题,而不是.net core web api问题-stackoverflow.com/questions/46764769/…
标签: c# .net-core asp.net-core-webapi asp.net-apicontroller