zoukankan      html  css  js  c++  java
  • 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?}");
                });
  • 相关阅读:
    动手动脑
    选课1.0
    四则运算
    JAVA异常处理机制资料整理
    JAVA学习日报(快乐作业) 10.27
    JAVA学习日报(快乐作业) 10.20
    JAVA学习日报 9/30
    JAVA学习日报 9/28
    JAVA学习日报 9/27
    JAVA学习日报 9/26
  • 原文地址:https://www.cnblogs.com/daxiongblog/p/13724663.html
Copyright © 2011-2022 走看看