Asp.net Core MVC 动态路由

动态路由 asp.net core 3.0 就支持了

csharp 复制代码
 // 映射关系
 public class TranslationDatabase
 {
     private static Dictionary<string, Dictionary<string, string>> Translations
      = new Dictionary<string, Dictionary<string, string>>
  {
     {
         "en", new Dictionary<string, string>
         {
             { "orders", "orders" },
             { "list", "list" }
         }
     },
     {
         "de", new Dictionary<string, string>
         {
             { "bestellungen", "orders" },
             { "liste", "list" }
         }
     },
     {
         "pl", new Dictionary<string, string>
         {
             { "zamowienia", "order" },
             { "lista", "list" }
         }
     },
  };

     public async Task<string> Resolve(string lang, string value)
     {
         var normalizedLang = lang.ToLowerInvariant();
         var normalizedValue = value.ToLowerInvariant();
         if (Translations.ContainsKey(normalizedLang)
             && Translations[normalizedLang]
                 .ContainsKey(normalizedValue))
         {
             return Translations[normalizedLang][normalizedValue];
         }

         return null;
     }
 }
 
 //动态路由
 public class TranslationTransformer : DynamicRouteValueTransformer
 {
     private readonly TranslationDatabase _translationDatabase;

     public TranslationTransformer(TranslationDatabase translationDatabase)
     {
         _translationDatabase = translationDatabase;
     }

     public override async ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext
     , RouteValueDictionary values)
     {
         if (!values.ContainsKey("language")
             || !values.ContainsKey("controller")
             || !values.ContainsKey("action")) return values;

         var language = (string)values["language"];
         var controller = await _translationDatabase.Resolve(language,
             (string)values["controller"]);

         if (controller == null) return values;
         values["controller"] = controller;

         var action = await _translationDatabase.Resolve(language,
             (string)values["action"]);

         if (action == null) return values;
         values["action"] = action;

         return values;
     }
 }

参考资料

相关推荐
超爱吃士力架1 小时前
邀请逻辑
java·linux·后端
李小白662 小时前
Spring MVC(上)
java·spring·mvc
AskHarries3 小时前
Spring Cloud OpenFeign快速入门demo
spring boot·后端
isolusion4 小时前
Springboot的创建方式
java·spring boot·后端
zjw_rp4 小时前
Spring-AOP
java·后端·spring·spring-aop
TodoCoder5 小时前
【编程思想】CopyOnWrite是如何解决高并发场景中的读写瓶颈?
java·后端·面试
凌虚6 小时前
Kubernetes APF(API 优先级和公平调度)简介
后端·程序员·kubernetes
机器之心6 小时前
图学习新突破:一个统一框架连接空域和频域
人工智能·后端
.生产的驴7 小时前
SpringBoot 对接第三方登录 手机号登录 手机号验证 微信小程序登录 结合Redis SaToken
java·spring boot·redis·后端·缓存·微信小程序·maven
顽疲7 小时前
springboot vue 会员收银系统 含源码 开发流程
vue.js·spring boot·后端