尝试创建WebApi无法正常工作的链接

时间:2017-05-23 16:31:24

标签: c# asp.net-web-api asp.net-web-api-routing

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

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没有连接第二个Route,“GetUser”,并且是这样的:"http://localhost:52494/api/v1/Register/1"

1 个答案:

答案 0 :(得分: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,请将其包含在路由模板中

[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
    }
}