Return HTML from ASP.NET Web API

146,549

Solution 1

ASP.NET Core. Approach 1

If your Controller extends ControllerBase or Controller you can use Content(...) method:

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

ASP.NET Core. Approach 2

If you choose not to extend from Controller classes, you can create new ContentResult:

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

Legacy ASP.NET MVC Web API

Return string content with media type text/html:

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;
}

Solution 2

Starting with AspNetCore 2.0, it's recommended to use ContentResult instead of the Produce attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885

This doesn't rely on serialization nor on content negotiation.

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

Related videos on Youtube

Andrus
Author by

Andrus

Updated on July 08, 2022

Comments

  • Andrus
    Andrus almost 2 years

    How to return HTML from ASP.NET MVC Web API controller?

    I tried the code below but got compile error since Response.Write is not defined:

    public class MyController : ApiController
    {
        [HttpPost]
        public HttpResponseMessage Post()
        {
            Response.Write("<p>Test</p>");
            return Request.CreateResponse(HttpStatusCode.OK);
        }
     }
    
    • Stilgar
      Stilgar over 9 years
      Why are you using WebAPI if you want to return HTML? I mean this is what ASP.NET MVC and ASP.NET WebForms are for.
    • Andrus
      Andrus over 9 years
      Thank you, excellent. I changed controller to regular controller.
    • Patrick Desjardins
      Patrick Desjardins over 9 years
      @Stilgar One reason could have been that he does not use the MVC stack, neither any rendering engine but still want to provide a server facade to some Html. A use case can be that you have a Web Api that give some Html with a client side templating engine that will render everything in a later stage.
    • wiwi
      wiwi almost 7 years
      @Stilgar Another use case I encountered is returning an html page to provide feedback for an account creation confirmation, when the user clicks on the link you provide through email
  • Parshuram Kalvikatte
    Parshuram Kalvikatte over 7 years
    Its not supporting in ASP.NET MVC Core HttpResponseMessage
  • Andrei
    Andrei over 7 years
    @Parshuram I've just checked your statement. I can use HttpResponseMessage in ASP.NET Core. It is located under System.Net.Http.
  • Parshuram Kalvikatte
    Parshuram Kalvikatte over 7 years
    ohk thanks but now MediaTypeHeaderValue not supporting
  • guyfromfargo
    guyfromfargo over 6 years
    When I do this using ASP.NET MVC 5 I get the response. I don't get any of the HTML content back. All I receive is "StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StringContent, Headers: { Content-Type: text/html }"
  • Andrei
    Andrei over 6 years
    @guyfromfargo have you tried [Produces] approach?
  • philw
    philw over 6 years
    I could not get the "produces" answer to work at all on 2.0, this however works fine.
  • Pavel Samoylenko
    Pavel Samoylenko about 6 years
    If you want to show a html from file, just add "var content = System.IO.File.ReadAllText("index.html");"
  • James Scott
    James Scott about 6 years
    Yup, if you are using ASP.NET Core 2.0 this is the way to go!
  • Jose Manuel Ojeda
    Jose Manuel Ojeda almost 6 years
    for me the code above works perfect on my local iis express but in normal iis it throws an exception that can serialize the response Type 'System.Net.Http.StringContent' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.
  • Lingam
    Lingam about 4 years
    What if the HTML file is in the local directory and it also has css, js linked. How do we serve the file then?
  • carlin.scott
    carlin.scott almost 4 years
    For Razor Pages, you can call the PageModel Content() method instead of creating ContentResult directly. I'm not sure if this is available for Controllers as well.