Coder Perfect

The ASP.NET Web API returns HTML.

Problem

What is the best way to get HTML from an ASP.NET MVC Web API controller?

Since Response, I tried the code below but received a compilation problem. The term “write” isn’t defined:

public class MyController : ApiController
{
    [HttpPost]
    public HttpResponseMessage Post()
    {
        Response.Write("<p>Test</p>");
        return Request.CreateResponse(HttpStatusCode.OK);
    }
 }

Asked by Andrus

Solution #1

You can use the Content(…) function if your Controller implements ControllerBase or Controller:

[HttpGet]
public ContentResult Index() 
{
    return base.Content("<div>Hello</div>", "text/html");
}

You can develop new ContentResult: if you don’t want to extend from Controller classes.

[HttpGet]
public ContentResult Index() 
{
    return new ContentResult 
    {
        ContentType = "text/html",
        Content = "<div>Hello World</div>"
    };
}

Return string content with the text/html media type:

public HttpResponseMessage Get()
{
    var response = new HttpResponseMessage();
    response.Content = new StringContent("<div>Hello World</div>");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

Answered by Andrei

Solution #2

In this instance, it’s recommended to utilize ContentResult instead of the Produce attribute starting with AspNetCore 2.0. See https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885#issuecomment-322586885 for more information.

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

Answered by KTCO

Post is based on https://stackoverflow.com/questions/26822277/return-html-from-asp-net-web-api