ASP.NET Core 2.0 Web API AND HATEOAS

Problem

How to implement RESTful API and custom media types in ASP.NET Core.

Solution

Using the CRUD and Paging samples, we’ll add links for clients to interact with our API. Download the code with this post to get a working sample and sample HTTP requests (Postman export).

Add a custom media type when configuring MVC services,

Create types that would add links to output models being sent to the client,

Add links for the collection resource,

Add links for single resource,

The GET methods will return response based on media type,

Output for GET,

Discussion

The idea behind HATEOAS (Hypermedia As The Engine Of Application State) is to transfer links in the resource representations. The sample demonstrates how links can be provided for a collection and individual resources. The links represent the actions that can be performed on the resource at a given point in time.

Custom media types are used to more accurately specify the type of representation being exchanged. For instance it is true that we’re exchanging JSON, however, it is more accurate to specify that what we’re exchanging with clients is more than JSON, it is a special form of JSON i.e. our own representation / media type.

We could also have custom media types for input formatters,

And then use Action Constraints to restrict access to action methods,

The custom action constraint is a class inheriting from Attribute and implementing IActionConstraint,

Note
I didn’t go into theoretical details about REST and HATEOAS here because there are plenty of good resources available, my favorite is a book “REST in Practice” by Jim Webber.

Note
Postman file included with the sample contains HTTP requests for GET, POST, PUT, DELETE and PATCH.

Source Code

GitHub

Next Recommended Readings