Question:
How to add parameters to Razor pages?

In ASP.NET Core, Razor Pages allow you to create dynamic web pages with embedded C# code. You can add parameters to Razor Pages by defining properties in the @page directive and then accessing those properties within the page. 


You may try the codes below:

builder.Services.AddRazorPages(op =>

{

    op.Conventions.AddFolderRouteModelConvention("/", model =>

    {

        foreach(var selector in model.Selectors)

                {

            var c = selector.AttributeRouteModel.Template.ToString();

            selector.AttributeRouteModel = new AttributeRouteModel

            {

                Order = -1,

                Template = builder.Environment.EnvironmentName+"/"+c


            };

        }

    });

});


The output will show like this:



public class MyConstraint : IRouteConstraint

    {

        //add the enviroment here

        private static readonly string[] AllowedValues = new string[] { "Development", "Production" };


        public bool Match(

            HttpContext? httpContext, IRouter? route, string routeKey,

            RouteValueDictionary values, RouteDirection routeDirection)

        {

            if (!values.TryGetValue(routeKey, out var routeValue))

            {

                return false;

            }


            var routeValueString = Convert.ToString(routeValue, CultureInfo.InvariantCulture);


            if (routeValueString is null)

            {

                return false;

            }


            return AllowedValues.Contains(routeValueString, StringComparer.InvariantCultureIgnoreCase);

        }

    }


In program.cs:

builder.Services.AddRouting(options =>

    options.ConstraintMap.Add("myconstraint", typeof(MyConstraint)));

// Add services to the container.

builder.Services.AddRazorPages(op =>

{

    op.Conventions.AddFolderRouteModelConvention("/", model =>

    {

        foreach(var selector in model.Selectors)

                {

            var c = selector.AttributeRouteModel.Template.ToString();

            selector.AttributeRouteModel = new AttributeRouteModel

            {

                Order = -1,

                Template = "{enviroment:myconstraint}/" + c


            };

        }

    });

});


Answered by:> Ruikai Feng

Credit:> Stack Overflow


Read more:

>Testing react components using Hooks and Mocks

>Use Firebase Realtime Database with ASP.NET MVC App

>Setting up a Cloud Composer environment: Step-by-step guide

>Built Web API using ASP.NET (C#)

>Plugins and Presets for Vuejs project

>How to Create an array based on two other arrays in Php


Ritu Singh

Ritu Singh

Submit
0 Answers