How to return html file from Web API

Returning html content from Web API can be very useful, when you want to provide content that can be embedded into html page easily.

In this tutorial you will learn how you can return any html file, content like form, images, and templates from Asp.net Web API

In our webmthod we just need to add an attribute [Produces("text/html")], This attribute indicates that the output will be in html not a simple string

Return HTML content using Web API method
[HttpGet("{id}")]
[Produces("text/html")]
public ActionResult<string> Get(int id)
{
    string _result = "<b>Return HTML content using Web API method </b>";
    return _result;
}

.Net Web API returns html content

If you want to understand the difference between with and without [Produces("text/html")] attribute, here are two different outputs

Without [Produces("text/html")] : <b>Return HTML content using Web API method </b>

With [Produces("text/html")] : Return HTML content using Web API method

[Produces("text/html")] Attribute in Web API

In Asp.net Core Web Api the above [Produces("text/html")] attribute may not work straightaway, you may find some error, so here are some additional code you need to write to make things work for you

Step 1: Create a Formatter class

using Microsoft.AspNetCore.Mvc.Formatters;
namespace WebTrainingRoom
{
    public class HtmlOutputFormatter : StringOutputFormatter
    {
        public HtmlOutputFormatter()
        {
            SupportedMediaTypes.Add("text/html");
        }
    }
}

Step 2: Now add the formatter class in ConfigureServices method of Startup class (middleware pipeline)

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options => options.OutputFormatters.Add(new HtmlOutputFormatter()));
}

Now if you execute the method you will get same output as mentioned above

Let's look at another example of how we can return a complete html subscription form with additional html element like image, text fields etc from our web API method

return html from web api

Basically we will be reading the html content of that specified file and return the content from our web API method in Asp.net Core

But reading a file from local folder in Asp.net Core works little differently than earlier version of Asp.net, as we already learned in Asp.Net Core about middleware setup and how dependency injection pattern is used, So here we setup an environment variable using constructor.

[Route("api/[controller]")]
[ApiController]
public class subscribeController : Controller
{
    private IHostingEnvironment _env;
    public subscribeController(IHostingEnvironment env)
    {
        _env = env;
    }
}

Get the file location and read the content as a string in a local variable

[HttpGet("{id}")]
[Produces("text/html")]
public ActionResult<string> Get(int id)
{
var webRoot = _env.WebRootPath;
	
var fileContent=System.IO.File.ReadAllText(webRoot + "/templates/subscribe.html");
return fileContent;
}

Till here, we have successfully returned html content from our web API method, now we see how to capture the data in web API when the form is submitted.

Just think of any real-time situation where your API is providing a subscription form that can be integrated in any web client, so when the form is submitted from different client, the API should be able to capture all those data, let’s see how we can do that.

 
Return html file from Asp.net Web API
Learn Web API: creating API using C# .Net, post, update, delete, read using .net API, set security, check authentication, testing.

C# web service interview questions

Learn API development
Asp.Net C# Web API Examples | Join Asp.Net MVC Course