ASP.NET Core 3中使用動態控制器路由

 

創建動態路由轉換對象繼承 DynamicRouteValueTransformer

  public class SlugRouteValueTransformer : DynamicRouteValueTransformer
    {


        public SlugRouteValueTransformer()
        {

        }

        public override async ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
        {
            var requestPath = httpContext.Request.Path.Value;

            if (!string.IsNullOrEmpty(requestPath) && requestPath[0] == '/')
            {
                // Trim the leading slash
                requestPath = requestPath.Substring(1);
            }
            if (string.IsNullOrEmpty(requestPath))
            {
                return new RouteValueDictionary
                {
                    { "area", "Core" },
                    { "controller", "Home" },
                    { "action", "Index" },
                    { "id", "" }
                };
            }
       //此處可以自定義 也可 通過查詢數據庫來確定路由到何處

//可修改的values return values; } }

 

在startup中插入動態路由

 services.AddScoped<SlugRouteValueTransformer>();

 

 app.UseEndpoints(endpoints =>
            {
                endpoints.MapDynamicControllerRoute<SlugRouteValueTransformer>("/{**slug}");
                endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章