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.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.
Output FormatterSince 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
MVC OptionsFinally, in our startup, we need to add our new Output Formatter in the AddMVC extension method.
ResultsHere are two different outputs. The first is with an
Accept: application/jsonand the second is requestion Siren with