November Happy Hour will be moved to Thursday December 5th.

Custom Partial Router not work

Vote:
 

Hi Optimizely team,

I'm trying implement custom PartialRouter follow this Developer guide - Routing and seem it's not  working.

I created CustomPartialRouter as bellow:

namespace OptimizelyAlloy
{
    public class RegisteredStartPagePartialRouter : IPartialRouter<StartPage, StartPage>
    {
        public object RoutePartial(StartPage content, UrlResolverContext segmentContext)
        {
            // Get the next URL part
            var nextSegment = segmentContext.GetNextSegment(segmentContext.RemainingSegments);
            if (string.IsNullOrEmpty(nextSegment.Next.ToString()))
            {
                return content;
            }

            Console.WriteLine("Set route id : " + nextSegment.Next);
            
            // Put it in the 'id' parameter
            segmentContext.RouteValues.Add("id", nextSegment.Next.ToString());

            // And anything extra in the remaining path, which will 404 as this URL is then not valid
            segmentContext.RemainingSegments = nextSegment.Remaining;

            return content;
        }

        public PartialRouteData GetPartialVirtualPath(StartPage content, UrlGeneratorContext urlGeneratorContext)
        {
            return null;
        }
    }
}

Registed in DI and called UseTemplate as bellow

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddSingleton<IPartialRouter, RegisteredStartPagePartialRouter>();
}
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        // Required by Wangkanai.Detection
        app.UseDetection();
        app.UseSession();

        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        
        app.UseEndpoints(endpoints =>
        {
            // endpoints.MapControllerRoute(name: "Default", pattern: "{controller}/{action}/{id?}");
            // endpoints.MapControllers();
            // endpoints.MapRazorPages();
            
            endpoints.MapContent()
                .MapTemplate<StartPageController>("{id:string}");
        });
    }

Updated StartPageController to pass string parameter named "id" as bellow

public class StartPageController : PageController<StartPage>
{
    public IActionResult Index(StartPage currentPage, string id = "")
    {
        Console.WriteLine("id param from controller : " + id);
        
        var model = PageViewModel.Create(currentPage);

        // Check if it is the StartPage or just a page of the StartPage type.
        if (SiteDefinition.Current.StartPage.CompareToIgnoreWorkID(currentPage.ContentLink))
        {
            // Connect the view models logotype property to the start page's to make it editable
            var editHints = ViewData.GetEditHints<PageViewModel<StartPage>, StartPage>();
            editHints.AddConnection(m => m.Layout.Logotype, p => p.SiteLogotype);
            editHints.AddConnection(m => m.Layout.ProductPages, p => p.ProductPageLinks);
            editHints.AddConnection(m => m.Layout.CompanyInformationPages, p => p.CompanyInformationPageLinks);
            editHints.AddConnection(m => m.Layout.NewsPages, p => p.NewsPageLinks);
            editHints.AddConnection(m => m.Layout.CustomerZonePages, p => p.CustomerZonePageLinks);
        }

        return View(model);
    }
}

And when debug, I saw custom PartialRouter setted routesValues before go to StartPageController, but parameter still empty as image bellow:

CustomPartialRouterTest

#300763
Edited, Apr 26, 2023 11:45
Sameer Ajmal - Jan 28, 2024 10:44
Hi Dzung,

Did you find a solution for the Partial router not working ?
I have the exact same issue where I add a value to the RouteValues and can see them in Partial router but as soon as I return the content and come to the controller that added routeValue is not there.
Dzung Nguyen - Jan 29, 2024 2:39
Hi @Sameer Ajmal,
Not found any solution to make Partial router work. So I registered all custom route via Startup like @Luc's comment.
Sameer Ajmal - Jan 29, 2024 8:49
Thanks for replying
Using custom routes in Startup makes the Parital Router useless. For me this is a issue when upgrading from CMS 11 to 12.
I'll ask around a bit and let you know if I find a soultion to this :)
Sameer Ajmal - Mar 11, 2024 20:33
@Dzung
I got it it to work. You can see my comment on the post.
Hope it works for you as well :)
Vote:
 

Intresting in why would you add partial routing on startpage? what is the scenario here? Why not just route everyting to startpage controller?

endpoints.MapControllerRoute(name: "everygthingystart", pattern: "{id?}", defaults: new { controller = "StartPage", action = "Index" });

#300881
Apr 28, 2023 6:57
Dzung Nguyen - Apr 28, 2023 8:56
Hi Luc,
I'm upgrading code base from CMS 11 to CMS 12, current codebase using Partial Routing for passing parameter to PageController, the example above written in Alloy to make sure the issue raise with default configuration from Epi.
Your suggested code work as a alternative solution, but the issue with Partial Router still occurs.
Vote:
 

@Dzung 

So I finally got it to work here is the what I found in the documentation.

UrlResolverContext.RouteValues in RoutePartial method reflects HttpContext.RouteValues, which is unchangeable in ASP Net Core.

To add additional data to RouteValuesyou must use IHttpContextAccessor.HttpContext.Items or IHttpContextAccessor.HttpContext.Request.RouteValues. For example:

public class NewsPartialRouter : IPartialRouter<NewsContainer, NewsContent>
{
  private readonly IHttpContextAccessor _contextAccessor;
  
  public object RoutePartial(NewsContainer content, UrlResolverContext urlResolverContext)
  {
    _contextAccessor.HttpContext.Request.RouteValues.Add("paramName", paramValue);
    // or
    _contextAccessor.HttpContext.Item.Add("paramName", paramValue);
    // MVC controller will be:
    // public IActionResult Index(NewsContainer currentContent, object paramName)
  }
}
#316489
Feb 01, 2024 10:19
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.