Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Filipe Sousa 43 posts 205 karma points
    Feb 22, 2024 @ 11:22
    Filipe Sousa
    0

    Custom route for controller

    I have a pokemon page route in several websites in a single umbraco installation, let's call it pokemons/{id}/{slug}. This route is used to call a controller where I fetch a pokemon from an API and show it's details.

    It so happens that I need to move that route around in multiple websites. So in one of them it might sit at the root while at another one it might sit in a different path say my/pokemons/{id}/{slug}.

    I've written some code to set up the routes on startup:

    var context = _contextFactory.EnsureUmbracoContext().UmbracoContext;
    var pokemonContentType = context.Content.GetContentType("pokemonPage");
    var pokemonPages = context.Content.GetByContentType(pokemonContentType);
    
    // Get all unique routes for pokemon pages.
    var routes = pokemonPages
        .Select(page => new Uri(page.Url()))
        .Select(uri => uri.PathAndQuery.TrimStart('/') + "{id}/{slug}")
        .Distinct()
        .ToArray();
    
    for (int i = 0; i < routes.Length; i++)
    {
        var route = routes[i];
        _logger.Debug<RegisterCustomRoutes>($"Registering route for pokemon page: {route}");
    
        RouteTable.Routes.MapUmbracoRoute(
           "pokemonPage" + i,
           route,
           new
           {
               controller = "Pokemons",
               action = "PokemonPage"
           },
           new PokemonRouteHandler(_siteFactory),
           new
           {
               id = new GuidRouteConstraint()
           }
        );
    }
    

    Is this the best way to do it? I've looked at IContentFinder but it doesn't seem to be meant for calling controllers.

    What if I need to move the routes around after startup? I'm thinking of hooking up to the ContentService.Published and add the new route accordingly. Would this be the best way to do it?

  • Filipe Sousa 43 posts 205 karma points
    Feb 26, 2024 @ 11:52
    Filipe Sousa
    100

    For later reference, I found that Articulate v8 implements a solution to a similar problem: https://github.com/Shazwazza/Articulate/blob/v8/src/Articulate/Routing/ArticulateRoutes.cs

Please Sign in or register to post replies

Write your reply to:

Draft