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