Creating a custom ASP.NET Core Output Formatter

Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.

ASP.NET Core Output FormatterIf 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.

Output Formatter

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 application/vnd.siren+json

MVC Options

Finally, in our startup, we need to add our new Output Formatter in the AddMVC extension method.

Results

Here are two different outputs.  The first is with an Accept: application/json and the second is requestion Siren with Accept: application/vnd.siren+json

Stay Tuned

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 on Twitter

Software Architecture & Design

Get all my latest YouTube Vidoes and Blog Posts on Software Architecture & Design

Leave a Reply

Your email address will not be published. Required fields are marked *