首页 > 解决方案 > 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 的默认值,它也不起作用。

标签: c#.net-coreasp.net-core-webapiasp.net-apicontroller

解决方案


给你的 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
    }

}

希望能帮助到你


推荐阅读