Dan Schnau

How To Add Controllers To A Blazor Server App

Update November 2024

I wrote a much more detailed post about this subject here: https://danschnau.com/blog/how_to_add_a_Blazor_Server_App_to_an_ASPNET_Controller_Web_API


I spun up a new Blazor Server App and wanted to add an API controller, but out of the box it didn't work. It's funny, sometimes the things that you take for granted end up being hard to get past when they don't work how you expect.

I had to do these steps:

  1. In Program.cs, configure Controller routes. This is the "canonical" default:

    app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");

  2. That's basically it. Add a Controllers directory to the Server project, and instantiate an API controller. For example:

    using Microsoft.AspNetCore.Mvc;

    namespace MyApp.Server { [Route("/")] [ApiController] public class TestController : ControllerBase { [HttpGet("getdata")] public IActionResult GetData() { return Ok(new { data = new { foo = "bar" } }); } } }

After that an HTTP GET to /getdata would return the hard-coded object there.