Eugene
Eugene

Reputation: 277

How to localize URL's in .NET Core 2.x?

I've already setup and have the localization working, configured both in ConfigureServices() and in Configure() like:

var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
        app.UseRequestLocalization(locOptions.Value);
        app.UseRouter(routes =>
        {
            routes.MapMiddlewareRoute("{culture=en}/{*mvcRoute}", subApp =>
            {
                subApp.UseRequestLocalization(locOptions.Value);

                subApp.UseMvc(mvcRoutes =>
                {
                    mvcRoutes.MapRoute(
                        name: "default",
                        template: "{culture=en}/{controller=Home}/{action=Index}/{id?}");
                });
            });
        }).Run(NotFoundHandler);

and working like /fr/Home/Register but when it comes to links like <a asp-action="Register">Register</a> they still produce the default request culture, the en.

So the generated links are like /en/Home/Register instead of /fr/Home/Register

Is there something that I'm missing to make it work with links too?

Upvotes: 0

Views: 354

Answers (1)

Alexander
Alexander

Reputation: 9632

You are missing culture route value for link and that's why the default culture is set. It's possible to add it using asp-route-[data] attribute

<a asp-action="Register" asp-route-culture="fr">Register</a>

In order to retrieve current request culture you can use IRequestCultureFeature. Get feature in the view

@{
    var cultureFeature = Context.Features.Get<Microsoft.AspNetCore.Localization.IRequestCultureFeature>();
}

Use IRequestCultureFeature.RequestCulture.Culture to retrieve current culture

<a asp-action="Register" asp-route-culture="@(feature.RequestCulture.Culture)">Register</a>

Upvotes: 1

Related Questions