Returning HTML or any file using Asp.Net controller

I have updated this post to take asp.net core into consideration. If you are looking for an answer on how to do this in Web API in .Net Framework look further below in this post.

How to return HTML from an API controller in ASP.Net core

First off, I would suggest you use cshtml (Razor) and fire up a standard web page project template in your IDE if you wish to make a website. However if your use case is that you need to return HTML from an API Controller for whatever reason, here is what you need to do.

Let us say we have the following HTML:

<!DOCTYPE html>
<html>
<body>
    <h1>Hello World!</h1>
</body>
</html>

If this file is located in a folder Content, we can return its content from a controller using the following:

[ApiController]
[Route("[controller]")]
public class IndexController
{
    public ContentResult Get()
    {
        var fileContents = File.ReadAllText("./Content/HelloWorld.html");
        return new ContentResult
        {
            Content = fileContents,
            ContentType = "text/html"
        };
    }
}

In the above we get the contents using File.ReadAllText and return it using the ContentResult in ASP.Net core. The result is the following when you visit /index:

hello-world-html-from-controller

How to return HTML from a Web Api controller in .Net framework

I will start by mentioning that Web API is not meant to deliver HTML pages. If you wish to build a website please use regular MVC - or something else. With that being said, you can have different reasons for having to do this.

Below is an example of a controller that returns the content of a html file.

[HttpGet]
public HttpResponseMessage HelloWorld()
{
   var fileContents = File.ReadAllText(HttpContext.Current.Server.MapPath("~/Content/HelloWorld.html"));
   var response = new HttpResponseMessage();
   response.Content = new StringContent(fileContents);
   response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
   return response;
}

The above example is getting the path for the file through the HttpContext using MapPath. If you are not using IIS, then maybe you will only need to use Directory.GetCurrentDirectory().

var fileContents = File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "Content/HelloWorld.html"));

For this project I have the below structure in my project. I can get the html file by using the endpoint http://localhost:52774/api/web/helloworld

Structure of the project

That is it!

I hope you enjoyed this post on how to return HTML from a controller, please let me know in the comments if you did!