动态路由 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;
}
}
参考资料