busbina
busbina

Reputation: 579

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.

Upvotes: 4

Views: 3295

Answers (1)

busbina
busbina

Reputation: 579

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?}");
});

Upvotes: 12

Related Questions