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.
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.
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.
As KTCO pointed out here :
Starting with AspNetCore 2.0, it's recommended to use
ContentResultinstead of theProduceattribute
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With