【发布时间】:2019-09-29 03:10:57
【问题描述】:
我前段时间问how to add some kind of localized url's,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
}
});
}
}
}
}
【问题讨论】:
标签: c# asp.net-core razor-pages asp.net-core-2.2