首页 > 解决方案 > 尝试使用路由属性 web api 从 uri 绑定一个 int[] 数组(作为对象属性)

问题描述

我使用 .Net Framework 构建了一个 API,我有一个控制器

[RoutePrefix("api/student")]
public StudentController : ApiController
{
    private readonly IService service;
}

public StudentController(IService service)
{
   this.service = service
}

[HttpGet, Route("getStudents/{Ids:int}")]     
public async Task<IHttpActionResult> GetStudents([FromUri]GetStudentsRequest request)
{
   //bla bla bla 
}

GetStudentsRequest 类是

public class GetStudentsRequest 
{
   public int[] Ids { get; set; }
}

我想在一个请求中传递多个 id,但问题是如何通过邮递员传递例如 3 个 id?

还是我必须更改属性?

我只想要来自 uri 而不是来自身体!

我试试这个将整数数组传递给 ASP.NET Web API? 排名最高的答案 localhost:XXXXX/api/student/getStudents?Ids=1&Ids=2 但没有用。不同的是我有一个具有数组属性的对象。

标签: c#.netasp.net-web-apipostman

解决方案


最后我解决了。以供将来参考,如果有人将 int 数组作为请求对象中的属性,则必须修改

路由属性

正确的是

[HttpGet, Route("getStudents")]  //i remove /{Ids:int} 
public async Task<IHttpActionResult> GetStudents([FromUri]GetStudentsRequest request)
{
   //bla bla bla 
}

并且 uri 是 localhost:XXXXX/api/student/getStudents?Ids=1&Ids=2

如果有人有更好的解决方案,请发布!


推荐阅读