aspnetcore: Returning HTML using Produces("text/html") causes 406 response

After upgrading to ASP.NET Core 2.0, [Produces("text/html")] doesn’t seem to work anymore. I am returning a string in my action using Ok(str) with that attribute specified.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 18 (12 by maintainers)

Most upvoted comments

The StringOutputFormatter used to ignore content types entirely and it no longer does this - it will only output text/plain. If you want it to output strings as text/html then you can add that as well.

options.OutputFormatters.OfType<StringOutputFormatter>().Single().SupportedMediaTypes.Add("text/html");

Personally I would just use Content(...) for this. You have the HTML text, and the content type already decided. This doesn’t rely on serialization nor on content negotiation.

Yeah. The docs seem to support this.

I’ve added this for now:

public class HtmlOutputFormatter : StringOutputFormatter
{
    public HtmlOutputFormatter()
    {
        SupportedMediaTypes.Add("text/html");
    }
}
services.AddMvc(options => options.OutputFormatters.Add(new HtmlOutputFormatter()));