如何在请求中传递字符串列表?

How can I pass a list of strings within a request?

我正在为我的应用程序使用 Refit 库,我需要调用其他服务。我需要获取所有具有我传递的 ID 的实体。

我尝试了 [Body] 属性,但仍然无效。我设法传递了一个请求,但是当我肯定传递现有的 IEnumerable 时,另一个服务获得的 id 列表为空。

我的 IRefitProxy:

[Get("/students/allByIds")]
Task<IEnumerable<Student>> GetStudentsById(IEnumerable<string> ids);

另一个服务的 API:

[RoutePrefix("api/students")]
[Route("allByIds")]
[HttpGet]
public IEnumerable<Student> AllByIds(IEnumerable<string> ids)
{
//ids here is null!

//call my repository blablabla
return students;
}

我传递了一个 array/List 字符串,结果为空。路径没问题,因为我设法进入了带有断点的方法。我怎样才能正确通过它?

不确定您如何调用 API 的端点。但是您是否尝试过在您的方法参数中使用 FromUri 属性?

[Get("/students/allByIds")]
Task<IEnumerable<Student>> GetStudentsById([FromUri] IEnumerable<string> ids);

然后您应该可以像这样调用:

?ids=11&ids=12&ids=13

或者甚至通过 JavaScript.

传递一个字符串数组

我设法解决了这个问题。添加 [Query(CollectionFormat.Multi)] 解决了问题。

[Get("/students/allByIds")] Task<IEnumerable<Student>>GetStudentsById([Query(CollectionFormat.Multi)]IEnumerable<string> ids);

接收API需要有[FromUri]属性。希望对大家有帮助!