我之前问过一个问题如何添加本地化的URL, 其中IPageRouteModelConvention
发挥了完美的作用。
有了它,我可以使用不同语言/名称的路由。
如果我使用
www.domain.com/nyheter
(瑞典语)或www.domain.com/sistenytt
(挪威语),我仍然只发现在 RouteData
中,使用了 News
路由(RouteData.Values["page"]
)。
我该如何获取哪个版本?
我知道我可以检查/解析 context.Request.Path
,但想知道是否有一个内置的属性可以直接给我它。
在
startup
中。services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddRazorPagesOptions(options =>
{
options.Conventions.Add(new LocalizedPageRouteModelConvention(new LocalizationService(appsettings.Routes)));
});
appsettings.Routes
从appsettings.json
中读取。
"Routes": [
{
"Page": "/Pages/News.cshtml",
"Versions": [ "nyheter", "sistenytt" ]
},
and so on....
]
这个类
public class LocalizedPageRouteModelConvention : IPageRouteModelConvention
{
private ILocalizationService _localizationService;
public LocalizedPageRouteModelConvention(ILocalizationService localizationService)
{
_localizationService = localizationService;
}
public void Apply(PageRouteModel model)
{
var route = _localizationService.LocalRoutes().FirstOrDefault(p => p.Page == model.RelativePath);
if (route != null)
{
foreach (var option in route.Versions)
{
model.Selectors.Add(new SelectorModel()
{
AttributeRouteModel = new AttributeRouteModel
{
Template = option
}
});
}
}
}
}