使用Url.Link与属性中的WebAPI 2路由 [英] Using Url.Link with Attribute Routing in Webapi 2

查看:273
本文介绍了使用Url.Link与属性中的WebAPI 2路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用的WebAPI 2.当下面的方法显示了如何使用命名的路由这样做是为了一个Location头添加到我的HTTP响应。有谁知道,如果你可以使用属性的路由功能,被释放的WebAPI 2的一部分创建Url.Link?

I want to add a Location header to my http response when using webapi 2. The method below shows how to do this using a named route. Does anyone know if you can create the Url.Link using Attribute Routing feature that was released as part of webapi 2?

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

在此先感谢

推荐答案

您使用属性布线时可以使用RouteName与Ur.Link。

You can use RouteName with Ur.Link when using attribute routing.

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

<一个href=\"http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#route-names\">http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#route-names

这篇关于使用Url.Link与属性中的WebAPI 2路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆