Skip to content

Instantly share code, notes, and snippets.

@darrelmiller
Created October 29, 2014 15:24
Show Gist options
  • Save darrelmiller/52276dd06368039de197 to your computer and use it in GitHub Desktop.
Save darrelmiller/52276dd06368039de197 to your computer and use it in GitHub Desktop.
A HtmlFormatter to allow conneg of HTML in MVC6
public class HtmlFormatter : OutputFormatter
{
public HtmlFormatter()
{
SupportedEncodings.Add(Encodings.UTF8EncodingWithoutBOM); // Whatever this should be
SupportedEncodings.Add(Encodings.UTF16EncodingLittleEndian); // Whatever this should be
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/html"));
}
public override bool CanWriteResult(OutputFormatterContext context, MediaTypeHeaderValue contentType)
{
return true;
}
public override async Task WriteResponseBodyAsync(OutputFormatterContext context)
{
if (context.Object == null)
{
// if the value is null don't write anything.
return;
}
// Obviously this doesn't compile, but you get the idea
var viewData = new ViewDataDictionary<context.DeclaredType>(new DataAnnotationsModelMetadataProvider());
viewData.Model = context.Object;
var viewResult = new ViewResult();
viewResult.ViewData = viewData;
await viewResult.ExecuteResultAsync(context.ActionContext);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment