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

 // 映射关系
 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;
     }
 }

在这里插入图片描述

参考资料

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部