Generating Hypermedia links in a Web API

徘徊边缘 提交于 2019-12-02 19:07:45

I prefer option two (adding the hypermedia links later in the pipeline) and blogged about doing this yesterday.

The solution was to "enrich" my resources with hypermedia links before they are returned to the client using a message handler.

You can use the Hyprlinkr from github

I'm planning to use it in my next project as it seens to be nice and easy to do it and you can get it via nuget package.

In answering this question, it's instructive to look toward the ASP.NET MVC approach to handling this, since ASP.NET MVC may be viewed as a text/html-constrained version of Web API (manual content negotiation notwithstanding), and since it obviously heavily influenced the design of Web API.

Basically, we can use custom formatters to vary the representations based on the route or an action attribute. This is informed by the way ASP.NET MVC separates views from models. In an ASP.NET MVC project, a single model can be rendered by various view templates. Each of these view template essentially "hard-codes" transitional links (anchor, form, and link elements) into that particular representation of the model. The selection of view template is driven predominately by convention (controller and action name), but can also be hard-coded in the action.

The view engine and view-finding convention in ASP.NET MVC can be considered a custom Web API formatter. This can be generalized such that, for each supported media type, a custom formatter uses route details--and optionally an attribute applied to the invoked action method--to define the resource state. (Under this convention, there is benefit in choosing action names that reflect the state of the resource.) Once the formatter knows the state of the resource, it can delegate to state-specific formatting code. In this code is where state-specific links would defined.

This state-specific formatting code could also delegate to other subformatters, much the same way Razor views support composition of partial views.

I've added my solution here

It uses class and property attributes in combination with an ApiController extension method to populate a ResourceLink object in your entity. It can also populate links for any collection properties. It's not the finished article but it is quite intuitive and will make a good start.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!