# 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](https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation) NuGet package.
1. Update `Startup.cs`:

   - Change `services.AddControllers()` to `services.AddControllersWithViews()`. (See the Remarks section of [the documentation](https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.mvcservicecollectionextensions.addcontrollerswithviews?view=aspnetcore-6.0#microsoft-extensions-dependencyinjection-mvcservicecollectionextensions-addcontrollerswithviews(microsoft-extensions-dependencyinjection-iservicecollection) for more details about what this does.)
   - Add these method calls:
```csharp
    services
        .AddRazorPages()
        .AddRazorRuntimeCompilation();
```

1. Add a Controller with a route. For example, if your Razor view is to display invoices, the controller could be something like this:
```csharp
    [Route("[controller]")]
    public class InvoicesController : Controller
    {
        [AllowAnonymous]
        public async Task<IActionResult> Index(CancellationToken cancellationToken)
        {
            var invoices = await GetInvoicesAsync(cancellationToken);
    
            return View(invoices);
        }
    }
```
1. 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.
