简体   繁体   中英

Return HTML from ASP.NET Web API ASP.NET Core 2 and get http status 406

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM