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

参考资料

相关推荐
A_aspectJ1 小时前
‌Spring MVC的主要组件有哪些?
java·spring·mvc
Ellie陈1 小时前
Java已死,大模型才是未来?
java·开发语言·前端·后端·python
wclass-zhengge2 小时前
SpringBoot篇(运维实用篇 - 临时属性)
运维·spring boot·后端
2401_857600952 小时前
商场应急管理:SpringBoot技术解决方案
java·spring boot·后端
半夏之沫3 小时前
✨最新金九银十✨大厂后端面经✨
java·后端·面试
小宇3 小时前
The valid characters are defined in RFC 7230 and RFC 3986
java·开发语言·后端·tomcat
Moment3 小时前
💯💯💯 历经四个月,我们开源了一个协同的在线代码编辑器,还支持执行 Node 项目哦!
前端·后端·github
鹿屿二向箔3 小时前
【毕业论文+源码】基于SSM(Spring + Spring MVC + MyBatis)的房屋租赁系统
spring·mvc·mybatis
景天科技苑4 小时前
【Golang】Go语言中如何进行包管理
开发语言·后端·golang·go mod·go语言包管理·go包管理·go sum