DEV Community

Sebastiaan Janssen
Sebastiaan Janssen

Posted on • Updated on

Create a plain dotnet, routed API controller in Umbraco

This is a very quick blog post, blink and you'll miss it! 😉

While building something the other day I suddenly had the need for a route that would output some JSON data. I didn't need anything from Umbraco, just some plain old (modern!) dotnet - yes this is for Umbraco 9+.

I thought I'd have to register routes in Startup.cs and that I'd have to add a route to ReservedPaths in appSettings.json, but.. to my surprise: none of that is needed, nice and easy and contained in 1 single .cs file.

So without further ado, here's the example:

using Microsoft.AspNetCore.Mvc;

namespace Cultiv.Controllers;

[ApiController]
[Route("api/[controller]")]
[Produces("application/json")]
public class GreetMeController : ControllerBase
{
    [HttpGet]
    public ActionResult Get([FromQuery]string name)
    {
        var value = new MyModel
        {
            Introduction = "Hello",
            Name = string.IsNullOrWhiteSpace(name) ? "World" : name
        };

        return new JsonResult(value);
    } 
}

public class MyModel
{
    public string Introduction { get; set; }
    public string Name { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

The interesting part here is the Route attribute, where [controller] will be replaced with the controller name, GreetMe, so the route becomes api/GreetMe and the Get method is what will respond to any Get request coming in.

This results in a nice JSON string response with the proper application/json response header:

Image description

This is called attribute routing and you can do a LOT more with it, check out the Microsoft documentation for more information.

That's it, that's the post! Just wanted to save it here to my external brain so I can find it in the future, hopefully it will help someone else as well.

Top comments (0)