加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-web-api – 在Webapi中使用Url.Link与属性路由2

发布时间:2020-12-15 19:01:52 所属栏目:asp.Net 来源:网络整理
导读:我想在使用webapi 2时向我的http响应添加一个Location头。下面的方法显示了如何使用一个命名的路由。有谁知道你是否可以使用作为webapi 2的一部分发布的属性路由功能创建Url.Link? string uri = Url.Link("DefaultApi",new { id = reponse.Id });httpRespon
我想在使用webapi 2时向我的http响应添加一个Location头。下面的方法显示了如何使用一个命名的路由。有谁知道你是否可以使用作为webapi 2的一部分发布的属性路由功能创建Url.Link?
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;
    }
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读