A typical web API returns JSON or XML responses. However, rare cases exist where we need to return responses in other formats. In this article, we are going to learn how to return HTML from ASP.NET Core Web API. We will also state some use cases for this type of API.

To download the source code for this article, you can visit our GitHub repository.

Let’s dive in.

Return HTML From ASP.NET Core Web API

We return HTML from an ASP.NET web API endpoint by specifying a return type of ContentResult:

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!
[HttpGet]
public ContentResult Index()
{
    var html = "<p>Welcome to Code Maze</p>";

    return new ContentResult
    {
        Content = html,
        ContentType = "text/html"
    };
}

Here, we create an endpoint that returns the HTML with the text “Welcome to Code Maze”. 

The ContentResult class has three properties; Content, ContentType and StatusCode. For HTML response, we create a ContentResult instance and populate the ContentType property with "text/html".

Use ControllerBase.Content Method

We can only use this method for controllers that derive from ControllerBase. Let’s see what we mean by that:

public class UserController : ControllerBase { }

The ControllerBase.Content() method returns a ContentResult object. This method has several overloads, and we will be using an overload that accepts two string parameters. The first string represents the content of the HTML while the last is the content-type which for HTML is "text/html".

Let’s see how we can use this method:

[HttpGet("verify")]
public ContentResult Verify()
{
    var html = "<div>Your account has been verified.</div>";

    return base.Content(html, "text/html");
}

Since our controller derives from ControllerBase, we simply call base.Content() and pass the required parameter to return the desired HTML.

Returning Static HTML

For static HTML, the content of the page is the same for all the visitors. If the HTML we intend to render is static, we can read it from an HTML file directly.

First, we create our static HTML file within our project:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Verification Successful</title>
</head>
<body>
    <h1>Profile Verified</h1>
    <p>Thank you for verifying your profile.</p>
</body>
</html>

Then we read the content and return its result:

[HttpGet("confirm-verify")]
public ContentResult ConfirmVerify()
{
    var html = System.IO.File.ReadAllText(@"./assets/verified.html");

    return base.Content(html, "text/html");
}

In this case, we place our static HTML named “verified.html” within the assets folder in the root directory of our project. By doing this we make our code more readable. This comes in handy when we display HTML with large content.

Returning Dynamic HTML

Dynamic HTML like the name suggests will show different contents for different viewers. Since we already know that we pass our HTML content as a string we can manipulate it that way. For readability, we are going to create a separate HTML file as we did in our previous example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome to Codemaze</h1>
    <p>We are glad to have you, {{name}} as a member.</p>
</body>
</html>

As we can see, the content of our HTML is quite basic. The “{{name}}” placeholder within the body tag will come in handy later on.

Let’s then read the content from this HTML file:

protected string WelcomeHTML(string name)
{
    var html = System.IO.File.ReadAllText(@"./assets/welcome.html");

    html = html.Replace("{{name}}", name);

    return html;
}

Within our controller, we create a private WelcomeHTML method that accepts and returns a string. This method reads the HTML file we have created and replaces the placeholder “{{name}}” with the parameter name.  This placeholder is the unique identifier we are using to make the page dynamic, and pass different names into it.

Finally, let’s create our API endpoint:

[HttpGet("welcome")]
public ContentResult Welcome(string name)
{
    var html = WelcomeHTML(name);

    return base.Content(html, "text/html");
}

We just create an API endpoint that returns a dynamic page while making our code as readable as possible.

When Do We Want to Return HTML From ASP.NET Core Web API

Let’s inspect some use cases where we will return HTML from an API:

One of the use cases would be when we want to provide feedback on an account or profile confirmation after the users click on the link sent to their email.

Also, another use case is when we display content for solutions without a front end. For example, an API As A Service without a front-end can use this to display some important information such as Terms and Conditions or receipts in the case of an e-commerce API.

Conclusion

In this article, we have seen how to return HTML from ASP.NET Core Web API. We have also seen how we can return both static and dynamic HTML while making our code readable.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!