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

参考资料

相关推荐
草莓base36 分钟前
【手写一个spring】spring源码的简单实现--容器启动
java·后端·spring
Ljw...1 小时前
表的增删改查(MySQL)
数据库·后端·mysql·表的增删查改
编程重生之路1 小时前
Springboot启动异常 错误: 找不到或无法加载主类 xxx.Application异常
java·spring boot·后端
薯条不要番茄酱1 小时前
数据结构-8.Java. 七大排序算法(中篇)
java·开发语言·数据结构·后端·算法·排序算法·intellij-idea
qq_17448285759 小时前
springboot基于微信小程序的旧衣回收系统的设计与实现
spring boot·后端·微信小程序
锅包肉的九珍9 小时前
Scala的Array数组
开发语言·后端·scala
心仪悦悦9 小时前
Scala的Array(2)
开发语言·后端·scala
2401_8827275710 小时前
BY组态-低代码web可视化组件
前端·后端·物联网·低代码·数学建模·前端框架
心仪悦悦10 小时前
Scala中的集合复习(1)
开发语言·后端·scala
阿芯爱编程10 小时前
商品折扣后的最终价格单调栈
java·后端·算法