asp.net核心Web API-相同的URL,具有不同的查询参数

问题描述 投票:0回答:1

我有一个如下的控制器类:

[Route("api/[controller]")]
public class ItemController : Controller
{
    //GET api/item?employId=1009
    [HttpGet]
    public List<ItemViewModel> GetByEmployId([FromQuery]long employId) {
            return new List<ItemViewModel>() {
                new ItemViewModel(),
                new ItemViewModel(),
                new ItemViewModel()
            };
    }

    // GET api/item?managerId=1009
    [HttpGet]
    public List<ItemViewModel> GetByManagerId([FromQuery]long managerId) {
        return new List<ItemViewModel>();
    }
}

对于第一个URL(http://localhost/api/item?employId=1),Web API可以返回结果。但是对于第二个URL(http://localhost/api/item?managerId=2),Web api返回HTTP代码为500的错误。有人可以帮忙为什么会这样吗?谢谢。

出于某种原因,我无法使用Web api项目进行调试。

asp.net-web-api asp.net-core asp.net-core-webapi asp.net-web-api-routing
1个回答
0
投票

有点过时,但是即使有人遇到相同的问题,也可以在这里找到答案。为此,您只需将查询参数添加为函数参数。使用相同的示例。

[Route("api/[controller]")]
public class ItemController : Controller
{

    [HttpGet]
    [Route("")]
    public List<ItemViewModel> Get([FromQuery]long employId, [FromQuery] long managerId) {
            if(employId != null){
                    return new List<ItemViewModel>() {
                new ItemViewModel(),
                new ItemViewModel(),
                new ItemViewModel()
              };
             }
            if(managerId != null){

               return new List<ItemViewModel>();
           }

          return new List();

    }


}

© www.soinside.com 2019 - 2024. All rights reserved.