On an NET Core 7 Razor Pages project I am using route localization.
In Program.cs I have the following:
builder.Services.Configure<RequestLocalizationOptions>(x => {
x.DefaultRequestCulture = new RequestCulture("pt");
x.SupportedCultures = new List<CultureInfo> { new CultureInfo("en"), new CultureInfo("pt") };
x.SupportedUICultures = new List<CultureInfo> { new CultureInfo("en"), new CultureInfo("pt") };
x.RequestCultureProviders.Insert(0, new RouteDataRequestCultureProvider {
RouteDataStringKey = "culture",
UIRouteDataStringKey = "culture",
Options = x
});
});
WebApplication application = builder.Build();
application.UseStatusCodePagesWithReExecute("/error/{0}");
application.UseRequestLocalization();
// ...
My Razor Pages are as follows:
@page "/{culture?}/contact"
@model ContactModel
So when culture is defined the page would be in that culture.
When is it not defined then the page gets the default culture, e.g., "PT".
The problem is handling the errors. I am using Status Code redirect:
application.UseStatusCodePagesWithReExecute("/error/{0}");
If, for example, I visit a non existent page then I am redirected to /error/4o4:
@page "/errors/{code?}"
@model ErrorModel
However if I try to access "/abc" that is not a valid culture or a valid page I am not redirected to /error/4o4.
I should be redirected to /error/4o4 if I access a route that starts with a invalid culture or a invalid page route.
How can I do this?
I am not sure why you are not redirecting to the
non-existentpage. I have tried to reproduce your issue and I am getting the expected error page as you can see below:Possible Reason:
Make sure you have register below attribute on your
program.csfile:Note: Not sure if you already have these. In addtion, please check the page name spelled correctly
@page "/errors/{code?}"then it would be likeapplication.UseStatusCodePagesWithReExecute("/errors/{0}");This is the main point I am interested in. There is no straight forward solution for this. However, I have a workaround for you.
Implementation:
To meet your requirement, I will consider two things:
HttpContextHttpContextvalue I will check theCultureInfoUsing Middleware We can do that:
Middleware:
Note:
Make sure you have registered the middlware in
program.csfile as below:Output: