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

·

1 min read

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.