ApiControllerAttribute 和可选参数
Posted
技术标签:
【中文标题】ApiControllerAttribute 和可选参数【英文标题】:ApiControllerAttribute and optional parameters 【发布时间】: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问题-***.com/questions/46764769/…
【参考方案1】:
给你的 ApiController 一个路由
[Route("api/[controller]")]
[ApiController]
public class ReposController : ControllerBase
//GetAll api/repos
public IEnumerable<Employees> Getall()
//Your code
//GET api/repos/id
[HttpGet("id", Name = "Getid")]
public Employees GetEmployees(int id)
//Your code
希望对你有帮助
【讨论】:
以上是关于ApiControllerAttribute 和可选参数的主要内容,如果未能解决你的问题,请参考以下文章