c# - ApiControllerAttribute 和可选参数
问题描述
阅读 using 的所有优点ApiControllerAttribute
,但是,如果我们希望在使用此属性作为查询参数时具有可选参数,则它不起作用。它仍然将所有参数验证为强制参数。知道如何使它成为可选的吗?
[ApiController]
public class testController: ControllerBase
{
[HttpGet("employees/{id?}")]
public List<Employees> GetAll(int? id)
{
// gets all employees or by id
}
}
执行此代码时,它会一直期待id
。没有这个参数它就不会运行。
编辑:即使传递了 id 的默认值,它也不起作用。
解决方案
给你的 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
}
}
希望能帮助到你
推荐阅读
- c# - 尝试根据表行的最高 ID 更新特定 SQL Server 表列时出错
- python - 在python中使用liblas和laspy读取las文件的问题
- html - Z-index 没有堆叠
- python - 如何在没有导入库的情况下在 python 文件中获取函数定义?
- java - 从android studio中的按钮单击访问url
- javascript - 如何使用 ArrayBuffer/ArrayBufferView 通过 WebSocket 发送字符串和整数的 Javascript 数组?
- android - 更改 TextInputLayout 提示字体
- regex - 使用正则表达式查找包含在特殊字符中的字符串
- python - 如何从另一个经过训练的模型中提取模型
- haskell - Jake Wheat 的“Intro to Parsing with Parsec in Haskell”过时了吗?