Dan Schnau

How To Add Controllers To A Blazor Server App

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?}");
  1. 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.