Created
October 29, 2014 15:24
-
-
Save darrelmiller/52276dd06368039de197 to your computer and use it in GitHub Desktop.
A HtmlFormatter to allow conneg of HTML in MVC6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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