在Webapi 2中使用Url.Link和属性路由

时间:2013-11-27 04:41:39

标签: asp.net-web-api

我想在使用webapi 2时为我的http响应添加一个Location标头。下面的方法显示了如何使用命名路由执行此操作。有没有人知道您是否可以使用作为webapi 2的一部分发布的属性路由功能创建Url.Link?

string uri = Url.Link("DefaultApi", new { id = reponse.Id });
httpResponse.Headers.Location = new Uri(uri);

提前致谢

2 个答案:

答案 0 :(得分:53)

使用属性路由时,您可以将RouteName与Ur.Link一起使用。

public class BooksController : ApiController
{
    [Route("api/books/{id}", Name="GetBookById")]
    public BookDto GetBook(int id) 
    {
        // Implementation not shown...
    }

    [Route("api/books")]
    public HttpResponseMessage Post(Book book)
    {
        // Validate and add book to database (not shown)

        var response = Request.CreateResponse(HttpStatusCode.Created);

        // Generate a link to the new book and set the Location header in the response.
        string uri = Url.Link("GetBookById", new { id = book.BookId });
        response.Headers.Location = new Uri(uri);
        return response;
    }
}

http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#route-names

答案 1 :(得分:2)

您可以这样做:

[Route("{id}", Name="GetById")]
public IHttpActionResult Get(int id) 
{
    // Implementation...
}

public IHttpActionResult Post([FromBody] UsuarioViewModel usuarioViewModel)
    {
        if (!ModelState.IsValid)
            return BadRequest();

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

        var content = "a object";     
        return Created(link, content);
    }