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.
- Install the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package.
Update
Startup.cs
:- Change
services.AddControllers()
toservices.AddControllersWithViews()
. (See the Remarks section of the documentation for more details about what this does.) - Add these method calls:
services .AddRazorPages() .AddRazorRuntimeCompilation();
- Change
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); } }
- 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.