簡體   English   中英

Asp.net 內核 Razor 頁面訪問常量路由值

[英]Asp.net Core Razor Pages Access Constant Route Value

在 Asp.net Core 3.x Razor 頁面 web 站點中,我需要設置多個指向單個頁面的預定義常量路由名稱,然后在特定的 cshtml 頁面上訪問它們

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}'

然后在 PropertyList.cshtml.cs 中,我需要知道哪個類別被用作路由數據

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

我想出了這個解決方案。 首先,我創建了一個路由約束。

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]);
        }
    }

然后在 Startup.cs 中,我刪除了以前的路由名稱並添加了這個

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

在 PropertyList.cshtml 中

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

在 PropertyList.cshtml.cs 中

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

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

因此 CategoryName 包含該值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM