将数组传递给 .Net Core Web API 方法时总是得到 404

Always getting 404 when passing an array to a .Net Core Web API method

出于某种原因,我似乎无法将一组值传递到我的 Web API 方法。这是我的代码:

[HttpGet("api/values/get/{ids}")]
public JsonResult GetValues(string[] valueIds)
{
   //Do something
}

我试过通过以下网址调用它:

当我通过以下 URL 调用它时,没有得到 404 并且实际上调用了该方法,但是,该数组是空的:

我还尝试将属性 [FromQuery] 添加到方法签名中的参数前面,如下所示:

public JsonResult GetValues([FromQuery]string[] valueIds)

我似乎无法让它工作,尽管那里的每个教程都说它应该工作。在这里扯掉我的头发。

如果我错了请纠正我,但我认为您需要使用 []- 后缀命名查询参数。像这样:

http://localhost:5001/api/values/get?valueIds[]=das&valueIds[]=ewq

否则您可以很容易地检查您的 API 除了 UrlHelper。给自己生成一个 url:

var url = Url.Action("GetValues", new { valueIds = new [] { "das", "ewq" } });

删除 {ids} 前缀,因为操作选择器需要 ids 参数,但您没有在操作中传递它。

[HttpGet("api/values/get")]
public JsonResult GetValues(string[] valueIds)
{
   //Do something
}

并像这样应用请求;

http://localhost:5001/api/values/get?valueIds=das&valueIds=ewq

那么,让我们分解一下您所拥有的:

[HttpGet("api/values/get/{ids}")]
public JsonResult GetValues(string[] valueIds)
{
   //Do something
}
  1. 我建议删除 /get,因为您的请求方法是 HttpGet
  2. 中的 get
  3. 您指定的路线意味着通过了ids(它只是一个与get相同的变量,它只能是单数)即:

http://localhost:5001/api/values/get/id

您展示的示例。

http://localhost:5001/api/values/get/?valueIds=das&valueIds=ewq

get/?valueIds=das&valueIds=ewq甚至没有指定{ids}

到目前为止你的 /get/{ids} 路线是多余的。

尝试

[HttpGet("api/values")]
public JsonResult GetValues(string[] valueIds)
{
   //Do something
}

查询:http://localhost:5001/api/values?valueIds=das&valueIds=ewq

我建议继续阅读 REST API naming conventions