Skip to main content

Command Palette

Search for a command to run...

Adding a Razor view to a .NET 6 ASP.NET Core API project

Published
1 min read
Adding a Razor view to a .NET 6 ASP.NET Core API project

I recently needed to add a Razor view to an existing ASP.NET Core API project. This is a relatively straightforward task, and this article documents the necessary steps.

  1. Install the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package.
  2. Update Startup.cs:

    • Change services.AddControllers() to services.AddControllersWithViews(). (See the Remarks section of the documentation for more details about what this does.)
    • Add these method calls:
      services
         .AddRazorPages()
         .AddRazorRuntimeCompilation();
      
  3. Add a Controller with a route. For example, if your Razor view is to display invoices, the controller could be something like this:

     [Route("[controller]")]
     public class InvoicesController : Controller
     {
         [AllowAnonymous]
         public async Task<IActionResult> Index(CancellationToken cancellationToken)
         {
             var invoices = await GetInvoicesAsync(cancellationToken);
    
             return View(invoices);
         }
     }
    
  4. Add a view in a folder which matches the controller's class and method names. In this case, that would be: Views/Invoices/Index.cshtml.

That's it! You can now go to whatever the root URL for your API is, add /Invoices and the view will load.

Code & technical writing

Part 4 of 16

This series groups articles which discuss specific code or technical concepts (as opposed to the process of working, etc.) If the blog consisted of only these articles, it would be a technical blog.

Up next

Representing a number with no more than two decimal places

How encapsulation makes it almost impossible to use a value that breaks a business rule