Reputation: 83
as i'm new to Razor Pages concept in ASP.NET Core, i want to apply a general URL to pass the culture parameter to the route
i have done that using MVC but i would like also to apply it with Razor pages here is what i have done in MVC and its working as needed
routes.MapRoute(
name: "default",
template: "{culture}/{controller=Home}/{action=Index}/{id?}");
i have applied it with specific Page and its working too
options.Conventions.AddPageRoute("/RealEstate/Index", "{culture}/RealEstate");
but when i want to apply for all pages it doesn't work and i don't know what should be passed as a PageName
options.Conventions.AddPageRoute("*", "{culture}/{*url}");
also i want to exclude the admin folder from this convention to be siteName.com/admin instead of en-US/Admin also i need to set a default culture in the URL when the user opens the site for first time, like for example to be siteName.com and loads default culture, or even loads siteName.com/en-US by Default
Thanks.
Upvotes: 3
Views: 10271
Reputation: 83
Thanks for the helping of Kirk Larkin
i used his answer and i added a small modification to exclude Admin from the culture routing also to set default culture for the website when no culture chosen
options.Conventions.AddFolderRouteModelConvention("/", model =>
{
foreach (var selector in model.Selectors)
{
if (selector.AttributeRouteModel.Template.StartsWith("Admin"))
{
selector.AttributeRouteModel = new AttributeRouteModel
{
Order = -1,
Template =
selector.AttributeRouteModel.Template,
};
}
else
{
selector.AttributeRouteModel = new AttributeRouteModel
{
Order = -1,
Template = AttributeRouteModel.CombineTemplates(
"{culture=en-US}",
selector.AttributeRouteModel.Template),
};
}
}
});
Upvotes: 1
Reputation: 93003
You can apply a route model convention to a folder using AddFolderRouteModelConvention
. The docs have an example of how to do this, which I've taken and modified for your purposes:
options.Conventions.AddFolderRouteModelConvention("/", model =>
{
foreach (var selector in model.Selectors)
{
selector.AttributeRouteModel = new AttributeRouteModel
{
Order = -1,
Template = AttributeRouteModel.CombineTemplates(
"{culture}",
selector.AttributeRouteModel.Template),
};
}
});
This applies a convention to all pages, given that "/"
is set as the folder and therefore applies at the root level. Rather than adding a new selector as in the example I linked, this modifies the existing selector to prepend the {culture}
token, which you can access in your pages by name, e.g.:
public void OnGet(string culture)
{
// ...
}
Had we added a new selector, the pages would be accessible both with and without the culture, making it optional. With the approach I've shown, the {culture}
token is required, as indicated in the OP.
Upvotes: 8