Andrus Andrus - 5 months ago 623x
HTML Question

Return HTML from ASP.NET Web API

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
public HttpResponseMessage Post()
return Request.CreateResponse(HttpStatusCode.OK);


Return HTML string

Return string content with media type text/html:

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

Returning Razor view from Web API

You need to Install-Package RazorEngine using your NuGet console.

using RazorEngine;
using RazorEngine.Templating;

string razorTemplate = "Hello @Model!";
string html = Engine.Razor.RunCompile(
    modelType: typeof(string), 
    model: "Lorem Ipsum");

Now we can use code from the previous example to return HTML string from Web API.