动态路由 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;
}
}
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » Asp.net Core MVC 动态路由
发表评论 取消回复