Multilingual Asp.Net Core 3.1 MVC application does not showing language code in url

Viewed 459

I'm working on an ASP.NET CORE application with multi lingual content. The culture is getting change successfully and it can be viewed in application cookies as well.

enter image description here

But the URL not changing by language switch. What I have tried in startup is as follow:

Startup ConfigureServices:

services.AddLocalization(options => options.ResourcesPath = "Resources");

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix,
        options => { options.ResourcesPath = "Resources"; })
    .AddDataAnnotationsLocalization(options =>
    {
        options.DataAnnotationLocalizerProvider = (type, factory) =>
            factory.Create(typeof(ShareResource));
    });

Startup Configure:

var supportedCultures = new List<CultureInfo>()
{
    new CultureInfo("en"),
    new CultureInfo("de"),
    new CultureInfo("fr"),
    new CultureInfo("pt"),
    new CultureInfo("tr")
};

var options = new RequestLocalizationOptions()
{
    DefaultRequestCulture = new RequestCulture("en"),
    SupportedCultures = supportedCultures,
    SupportedUICultures = supportedCultures,
    RequestCultureProviders = new List<IRequestCultureProvider>()
    {
        new QueryStringRequestCultureProvider(),
        new CookieRequestCultureProvider()
    }
};
app.UseRequestLocalization(options);

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "defaultWithLang",
        pattern: "{lang}/{controller=Home}/{action=Index}/{id?}");
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

And in HomeController:

public IActionResult ChangeLang(string lang)
{
    Response.Cookies.Append(CookieRequestCultureProvider.DefaultCookieName,
        CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(lang)),
        new CookieOptions(){
            Expires = DateTimeOffset.UtcNow.AddYears(1)
        });

    return Redirect(Request.Headers["Referer"].ToString());
}

The URL I expected to show is like "http://domain/en/controller/action" but it is not changing by switching the language and is always like "http://domain/controller/action" without language code.

Is there anything else I have to add to my code in startup or somewhere else? Appreciated for any help.

1 Answers

what happens hen you manually set url?

right now, you are using default fallback route.

check this:

    routes.MapRoute(
        name: "LocalizedDefault",
        template: "{lang:lang}/{controller=Home}/{action=Index}/{id?}"
    );

    routes.MapRoute(
        name: "default",
        template: "{*catchall}",
        defaults: new { controller = "Home", action = "RedirectToDefaultLanguage", lang = "en" });

you can also add lang constraint

services.Configure<RouteOptions>(options =>
{
    options.ConstraintMap.Add("lang", typeof(LanguageRouteConstraint));
});

then add following lines just above route configuration

var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(options.Value);
Related