Generating Hypermedia links in a Web API

后端 未结 4 682
星月不相逢
星月不相逢 2021-02-01 19:12

I\'m curious to know how others have dealt with the issue of generating hypermedia links for their web APIs? Specifically, I\'m using ASP.NET Web API, and am torn between having

4条回答
  •  清歌不尽
    2021-02-01 19:35

    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.

提交回复
热议问题