Asp.net web api 在Webapi 2中使用Url.Link和属性路由
在使用webapi 2时,我想在http响应中添加一个位置头。下面的方法显示了如何使用命名路由执行此操作。有人知道您是否可以使用作为webapi 2的一部分发布的属性路由功能创建Url.Link吗Asp.net web api 在Webapi 2中使用Url.Link和属性路由,asp.net-web-api,Asp.net Web Api,在使用webapi 2时,我想在http响应中添加一个位置头。下面的方法显示了如何使用命名路由执行此操作。有人知道您是否可以使用作为webapi 2的一部分发布的属性路由功能创建Url.Link吗 string uri = Url.Link("DefaultApi", new { id = reponse.Id }); httpResponse.Headers.Location = new Uri(uri); 提前感谢使用属性路由时,您可以将RouteName与Ur.Link一起使用 publ
string uri = Url.Link("DefaultApi", new { id = reponse.Id });
httpResponse.Headers.Location = new Uri(uri);
提前感谢使用属性路由时,您可以将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;
}
}
您可以执行以下操作:
[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);
}
这个真的很有帮助。塔克斯