If you follow my blog, you may also know that I’ve blogged a bit about Hypermedia. Because I’m a fan, I’ve decided to start creating an custom ASP.NET Core Output Formatter to handle the Siren hypermedia specification (application/vnd.siren+json).
All the code samples in this blog post are pulled from a sample application of the game Hangman. I’m creating it in ASP.NET Core. I will eventually pull out the Output Formatter and create a repo on GitHub and a Nuget.
Since I’m handling Text, I’m going to be deriving from the TextOutputFormatter. This requires you to implement two methods:
bool CanWriteType(Type type)
This method determines if your output formatter can handle the type returned from your controller action.
Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
Handle how yo want to transform the object returned from your controller action.
Lastly, you also need to define which media types your output formatter will handle. In other words, when the client sends an Accept: header, which values apply to your output formatter.
In my case, Siren uses
Finally, in our startup, we need to add our new Output Formatter in the AddMVC extension method.
Here are two different outputs. The first is with an
Accept: application/json and the second is requestion Siren with
If you’re interested in supporting Siren in your ASP.NET Core MVC applications, I plan on publishing my small library soon to GitHub as well as Nuget.
Have you created a custom output formatter? I’d love to hear what your creating! Let me know on Twitter or in the comments.Follow @codeopinion