2

Is there any solid guidance for generating hyperlinks for your resources in ASP.NET WebAPI? I've read a couple of posts on this:

http://codebetter.com/glennblock/2012/01/08/hypermedia-and-web-api-design-brain-dump-and-samples/

http://blog.ploeh.dk/2012/04/17/HyperlinkingWithTheASPNETWebAPI.aspx

Although informative, there appears to be no concrete guidance from Microsoft or otherwise in terms of how best to implement links for your resources (i.e. object model implemented using DTOs at the service layer). If we are moving towards using WebAPI to implement a true RESTful service, hyperlinking is crucial and I would have expected built in support / guidance for this in WebAPI.

A simple example I'm trying to implement this for is using a Contact entity which has a collection of Addresses and a collection of SupportIncident. The class definitions based on the first article I've referenced would look something like so:

 public class Link 
{         
    public Uri Uri { get; set; } 
    public string Rel { get; set; }
    public string Name { get; set; } 
}

public class ContactDTO
{
    public int ID { get; set; }

    public string Name { get; set; }

    public IList<AddressDTO> Addresses { get; set; }

    public IList<IncidentDTO> Incidents{ get; set; }

    public IList<Link> Links { get; set; }

}

WebAPI is great at exposing this model over HTTP (xml/json) and the GET/PUT/POST/DELETE action on the resource but in order to build a true RESTful service I would like to know if a) Is there inherent support for link generation in WEBAPI? b) Is there proper guidance for exposing the model above containing links to resources and how should the API handle PUT/POST if a client sends links as part of the payload. Should these be ignored?

4

2 回答 2

1

在我看来,本·福斯特在这方面做得很好。请参阅以下博客文章:

基本思想是,您将通过消息处理程序在退出时修改ObjectContent'Value属性。该消息处理程序将这项工作委托给注册的所谓“响应丰富者”,并且每个人都有机会评估它是否可以丰富对象类型。

于 2013-02-10T09:51:09.277 回答
0

我在这里构建了一个示例应用程序,演示了在 Web API 中使用超媒体。这里还有一个https://github.com/webapibook/issuetracker 和 Amy Palamountain 这里有另一个很好的例子https://github.com/ammeep/hyper-library

使用 DTO 和链接的主要问题之一是默认情况下,这些 DTO 将被序列化为application/jsonapplication/xml。这些媒体类型都没有关于如何序列化链接的任何规范。因此,客户需要有关如何处理这些链接的带外知识。

要正确执行超媒体,您需要使用启用超媒体的媒体类型,例如 xhtml、hal、collection+json、json-ld、siren。

于 2014-01-14T14:07:24.967 回答