Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 676
Frank Monroe Avatar asked Oct 17 '17 15:10

Frank Monroe


People also ask

How do I return HTML page in Web API?

The first string represents the content of the HTML while the last is the content-type which for HTML is "text/html" . Since our controller derives from ControllerBase , we simply call base. Content() and pass the required parameter to return the desired HTML.

Can we use TempData in Web API?

It uses the keyvalue for passing the data and it has a need for typecasting. TempData: TempData is a dictionary that is derived from the TempDataDictionary class. The tempData Dictionary object persists only from one request to the next. You can mark one or more keys for retention using the keep method.


1 Answers

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.

like image 166
Frank Monroe Avatar answered Oct 22 '22 07:10

Frank Monroe