尝试创建 link 且 WebApi 不起作用

Trying to create a link with WebApi not working

在我的项目中,我需要创建一个带参数的 link,所以我是这样做的:

var link = new Uri(Url.Link("GetUser", new { id = 1 }));

static List<Students> std = new List<Students>()
{
    new Students(){id = 1, Nome = "Nathiel"},
    new Students() {id = 2, Nome = "Barros"}
};

还有接收 id 的方法:

[Route("{id:int}",Name = "GetUser")]
[HttpGet]
public async Task<HttpResponseMessage> Get(int id)
{
    var u = std.FirstOrDefault(x => x.id == id);

    var response = new HttpResponseMessage();
    response = Request.CreateResponse(HttpStatusCode.OK, u);

    var task = new TaskCompletionSource<HttpResponseMessage>();
    task.SetResult(response);
    return await task.Task;
}

问题是,URL 没有连接第二条路线 "GetUser",而是这样的:"http://localhost:52494/api/v1/Register/1"

假设路由前缀是 api/v1/Register

[RoutePrefix("api/v1/Register")]
public class RegisterController : ApiController {
    [HttpGet]
    [Route("{id:int}",Name = "GetUser")] //Matches GET api/v1/Register/1
    public async Task<IHttpActionResult> Get(int id) {
        //...code removed for brevity
    }
}

那么这是设计使然。

路由名称用于标识生成路由时要使用的路由模板。

如果您想要 GetUser 在 URL 中,则将其包含在路由模板中

[RoutePrefix("api/v1/Register")]
public class RegisterController : ApiController {
    [HttpGet]
    [Route("GetUser/{id:int}",Name = "GetUser")] //Matches GET api/v1/Register/GetUser/1
    public async Task<IHttpActionResult> Get(int id) {
        //...code removed for brevity
    }
}