Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to do dynamic routing with Razor Pages?

I am looking for something like

app.UseEndpoints(endpoints =>
            {
                endpoints.MapDynamicControllerRoute<MyTransformer>($"{store}/{controller}/{action}");
            });

but for the razor pages routes. I dug though the AddRazorPagesOptions Conventions but nothing seemed to stand out. Checked Github and Google. Didn't find much there either.

like image 555
busbina Avatar asked Oct 25 '25 11:10

busbina


1 Answers

Answering my own question. Looks like there is a MapDynamicPageRoute that works with Razor Pages. You just have to do use the "page" key instead of "controller" and "action".

public class MyTransformer : DynamicRouteValueTransformer
{
    public MyTransformer()
    {

    }

    public override async ValueTask<RouteValueDictionary> TransformAsync(HttpContext
           httpContext, RouteValueDictionary values)
    {
        return await Task.Run(() =>
        {
            var rng = new Random();
            if (rng.NextDouble() < 0.5)
            {
                values["page"] = "/MyRazorPageA";
            }
            else
            {
                values["page"] = "/MyRazorPageB";
            }


            return values;
        });
    }
}

You also have to register the transformer endpoint with MapDynamicPageRoute like

app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    endpoints.MapDynamicPageRoute<MyTransformer>("rando/{path?}");
});
like image 115
busbina Avatar answered Oct 27 '25 00:10

busbina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!