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 小时前
Solon Cloud Gateway 开发:熟悉 ExContext 及相关接口
java·后端·gateway·solon
幸好我会魔法4 小时前
人格分裂(交互问答)-小白想懂Elasticsearch
大数据·spring boot·后端·elasticsearch·搜索引擎·全文检索
SomeB1oody4 小时前
【Rust自学】15.2. Deref trait Pt.1:什么是Deref、解引用运算符*与实现Deref trait
开发语言·后端·rust
lixww.cn4 小时前
ASP.NET Core MVC
c#·mvc·.netcore
何中应5 小时前
从管道符到Java编程
java·spring boot·后端
组合缺一5 小时前
Solon Cloud Gateway 开发:Route 的过滤器与定制
java·后端·gateway·reactor·solon
SomeB1oody5 小时前
【Rust自学】15.4. Drop trait:告别手动清理,释放即安全
开发语言·后端·rust
customer086 小时前
【开源免费】基于SpringBoot+Vue.JS贸易行业crm系统(JAVA毕业设计)
java·vue.js·spring boot·后端·spring cloud·开源
花心蝴蝶.7 小时前
Spring IoC & DI
java·后端·spring
半夏知半秋8 小时前
rust学习-所有权
开发语言·后端·学习·rust