20

This is a follow-up on Return HTML from ASP.NET Web API.

I followed the instructions but I get Error 406 in the browser. My code:

    [Produces("text/html")]
    [Route("api/[controller]")]
    public class AboutController : Controller
    {
        [HttpGet]
        public string Get()
        {
            return "<html><body>Welcome</body></html>"; 
        }
...

and, simply:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
}

When I remove the Produces line I get the plain text <html><body>Welcome</body></html> in the browser (no error).

What am I missing? Thanks.

1

2 Answers 2

49

As KTCO pointed out here :

Starting with AspNetCore 2.0, it's recommended to use ContentResult instead of the Produce attribute

The solution is:

[HttpGet]
public ContentResult Get()
{
    return new ContentResult {
        ContentType = "text/html",
        StatusCode = (int) HttpStatusCode.OK,
        Content = "<html><body>Welcome</body></html>"
    };
}

There is no need to change AddMvc (and there is no Produce attribute, of course).

I hope this helps someone.

Sign up to request clarification or add additional context in comments.

1 Comment

With NetCore v3.1 you can also use the int constants class StatusCodes (using Microsoft.AspNetCore.Http;), so that, we may use: StatusCode = StatusCodes.Status200OK
0

You need to add Content-Type header to text/html in the request which you are sending while using Produces attribute.

If you are sending through browser then it will work good because browser by default sends Content-type header as text/html

6 Comments

Not sure I understand what you mean: first the browser is sending the request so I have no control over this; second according to this learn.microsoft.com/en-us/aspnet/core/mvc/models/formatting "web browsers tend to supply Accept headers that include a wide array of formats, including wildcards. By default, when the framework detects that the request is coming from a browser, it will ignore the Accept header and instead return the content in the application's configured format (JSON unless otherwise configured)".
Thanks - I saw your edit. However that is exactly my question: it should work but it does not work for me. Why ? I though my question was clear about that since I did specify browser: "... followed the instructions but I get Error 406 in the browser".
Can you verify from developer tools of the browser that the content-type send by the browser for the request is text/html
Good idea. I tried 4 browsers and Postman but did not specifically checked the request Content-Type header. I will and get back here soon.
@FrankMonroe Did it helped?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.