Route to Umbraco API controller in .NET core
# help-with-umbraco
b
In an Umbraco 8 project, it has the following:
Copy code
RouteTable.Routes.MapHttpRoute(
    "ShortLinkApi",
    "link/{token}",
    new { controller = "ShortLink", action = "Process" },
    new { token = RegexExpressions.GuidRegex }
);
In have something like this in latest Umbraco 10:
Copy code
public static class UmbracoApplicationBuilderExtensions
{
    public static IUmbracoEndpointBuilderContext UseCustomRoutes(this IUmbracoEndpointBuilderContext app)
    {
        if (!app.RuntimeState.UmbracoCanBoot())
        {
            return app;
        }

        app.EndpointRouteBuilder.MapControllerRoute(
            name: "ShortLinkApi",
            pattern: "link/{token}",
            defaults: new { controller = "ShortLink", action = "Process" },
            constraints: new { token = RegexExpressions.GuidRegex }
        );

        return app;
    }
}

app.UseUmbraco()
    .WithMiddleware(u =>
    {
        u.UseBackOffice();
        u.UseWebsite();
    })
    .WithEndpoints(u =>
    {
        u.UseInstallerEndpoints();
        u.UseBackOfficeEndpoints();
        u.UseWebsiteEndpoints();
        u.UseCustomRoutes(); <!-- This -->
    });
However when accessing
/link/8FE56315-3843-4A50-A029-00189666534B
it doesn't hit the UmbracoApiController method as in v8.
Copy code
public class ShortLinkController : UmbracoApiController
{
    private readonly ShortLinkService _shortLinkService;

    public ShortLinkController(ShortLinkService shortLinkService)
    {
        _shortLinkService = shortLinkService;
    }

    [HttpGet]
    public IActionResult Process(Guid token)
    {
        var shortLink = _shortLinkService.GetShortLink(token);

        if (!string.IsNullOrWhiteSpace(shortLink?.RedirectUrl))
        {
            return Redirect(shortLink.RedirectUrl);
        }

        return NotFound();
    }
}
I could make it work using
[Route]
attribute on controller and action instead. But is there a way to map http routes?
Copy code
[Route("link")]
public class ShortLinkController : UmbracoApiController
{
    private readonly ShortLinkService _shortLinkService;

    public ShortLinkController(ShortLinkService shortLinkService)
    {
        _shortLinkService = shortLinkService;
    }

    [HttpGet]
    [Route("{token:guid}")]
    public IActionResult Process(Guid token)
    {
        var shortLink = _shortLinkService.GetShortLink(token);

        if (!string.IsNullOrWhiteSpace(shortLink?.RedirectUrl))
        {
            return Redirect(shortLink.RedirectUrl);
        }

        return NotFound();
    }
}
3 Views