Skip to main content

ELL Blog

ASP.NET Core Add HTML to Web Api

Suppose you wanted to add html to your web api project, how would you go about it?

Sure you may just write the HTML in the controller, but that’s not good enough if you want to return an actual webpage.

We need to integrate Razor pages to our application. In Program.cs,

builder.Services.AddRazorPages();  // add this
builder.Services.AddHttpContextAccessor();  // add this
var app = builder.Build();

app.MapRazorPages(); // add this, it doesn't matter if it is before or after MapControllers

Suppose we want to serve a page for

In your project folder, create Pages/About.cshtml

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor

<!DOCTYPE html>
    @Html.Raw("@")media only screen and (min-width: 950px) {
        .center {
            width: 30%;

<a href="@(HttpContextAccessor.HttpContext.Request.Path)@(HttpContextAccessor.HttpContext.Request.QueryString.ToUriComponent())">This pages url</a>
<p>a get request query for field name: @HttpContextAccessor.HttpContext.Request.Query["name"]</p>

How to escape @ in Razor Pages (cshtml)

To escape the @ in Razor pages, use @Html.Raw("@").