I sometime ago asked how to add some kind of localized url's, were IPageRouteModelConvention
came into play in a, for me, perfect way.
With that I'm able to have routes in different languages/names.
If I use www.domain.com/nyheter
(swedish) or www.domain.com/sistenytt
(norwegian) I still only find, in RouteData
, that the News
route were used (RouteData.Values["page"]
).
How do I get which version?
I know I can check/parse the context.Request.Path
but am wondering if there is a built-in property that will give me it instead.
In startup
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddRazorPagesOptions(options =>
{
options.Conventions.Add(new LocalizedPageRouteModelConvention(new LocalizationService(appsettings.Routes)));
});
appsettings.Routes
is read from appsettings.json
"Routes": [
{
"Page": "/Pages/News.cshtml",
"Versions": [ "nyheter", "sistenytt" ]
},
and so on....
]
The class
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
}
});
}
}
}
}