How to prevent ASP.NET Core from removing "/en/" from the URL?

Viewed 36

I just created a new ASP.NET Core Razor Pages project on .NET Core version 3.1, when I run using the Kestrel (console hosting), it opens a Web Browser with URL: https://localhost:5001 - which is OK.

Then when I add "/en/" suffix at the end of the URL and press Enter in the address bar, the page is reloaded but "/en/" is removed from the URL. ('https://localhost:5001/en/' - turns into 'https://localhost:5001' after page reload).

But if I do the same with "/ja/" instead of "/en/" like https://localhost:5001/ja/, the page is reloaded but "/ja/" remains exactly as I want.

What I'm trying to do is to catch "/en/" from the HttpContext.Request.Path - and do some processing from my Middleware.

But since ASP.NET Core keeps removing "/en/" from the URL I can't achieve my goal. I couldn't find any useful information on the Internet about my problem.

You can easily reproduce my problem. Just create a new ASP.NET Core Razor Page project on .NET Core version 3.1. Use Kestrel instead of IIS Express. Append "/en/" at the end of the URL and press ENTER. You'll see that "/en/" is removed. At least this happens on my computer. This problem is true only with "/en/" suffixes. I tried other language codes like "/ja/", "/hk/" - they persist, they are not removed from the URL.


UPDATE

It turns out the problem has nothing with .NET Core version 3.1. When I start my debug session from Visual Studio 2022 it launches a Web Browser (Microsoft Edge) and if I start new Incognito (InPrivate) session and type into the address bar "https://localhost:5001/en/", the "/en/" is not removed - exactly as I want, at least for the first attempt, and on further requests "/en/" keeps being removed.

I don't know maybe this is a Browser behavior or something related to Visual Studio debugger session, or the localization settings of my PC. I don't know. But now I know that it has nothing to do with .NET Core.

1 Answers

You can try to add {culture} to default route:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute("default", "{culture}/{controller=Home}/{action=Index}/{id?}");
});
Related