简体   繁体   中英

Asp.net Core Razor Pages Access Constant Route Value

Within the Asp.net Core 3.x Razor Pages web site, I need to set multiple predefined constant route names pointing to the single page and then access them on the particular cshtml.cs PageModel.

options.Conventions.AddPageRoute("/propertylist", "/properties/category1");
options.Conventions.AddPageRoute("/propertylist", "/properties/category2");
options.Conventions.AddPageRoute("/propertylist", "/properties/category3");
// I don't want any other categories to reach to the propertylist page so I didn't set it as '/properties/{categoryName}'

And then inside the PropertyList.cshtml.cs, I need to know what category was used as the route data

public async Task OnGet()
{
     // Get the route data to find the category name
}

I have come up with this solution. First I've created a route constraint.

public class PropertyListRouteConstraint : IRouteConstraint
    {
        private string[] categories = new[] {
            Constants.Routes.Categories.Category1,
            Constants.Routes.Categories.Category2,
            Constants.Routes.Categories.Category3
        };
        public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
        {
            return categories.Contains(values[routeKey]);
        }
    }

Then in Startup.cs, I removed the previous route names and added this

services.Configure<RouteOptions>(options =>
{
     options.ConstraintMap.Add("allowedpropertycats", typeof(PropertyListRouteConstraint));
});

In PropertyList.cshtml

@page "/properties/{categoryname:allowedpropertycats}"

In PropertyList.cshtml.cs

public class PropertyListModel : PageModel
    {        
        [BindProperty(SupportsGet = true)]
        public string CategoryName { get; set; }

        public async Task OnGet()
        {
           ...
        }
    }

So CategoryName contains the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM