LazZiya/XLocalizer

How to set default culture?

Closed this issue · 2 comments

Hello,

I am wondering how can I set a default culture for all routes if culture value isn't provided in the URL!
As you can see here the Identity razor page is working well without explicitly specifying the culture value.
image

Whereas in a view like this (controller - view) the page isn't working unless I explicitly provide a culture in the URL.
image

Thank you!!!

Hi @faresayyad ,

You need to setup multiple routes for the pages w/o culture parameter. e.g.:

[Route("")]
[Route("{culture}")]
[Route("{culture}/Home/Index")]
[Route("{culture}/Home/Index/{id?}")]

In order to avoid route conflicts, remove the code that automatically add culture param to all routes in startup:

services.AddRazorPages()
    // remove below line for razor pages setup
    // .AddRazorPagesOptions(ops => { ops.Conventions.Insert(0, new RouteTemplateModelConventionRazorPages()); });
    // or mvc setup
    // .AddMvcOptions(ops => { ops.Conventions.Insert(0, new RouteTemplateModelConventionMvc()); });

Last, I recommend to setup the culture cookie, so even if the route is not defined in the URL in this case XLocalizer will look for the route value in the cookie.

// Add required namespaces
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Http;

/// <summary>
/// Set culture cookie value
/// </summary>
/// <param name="cltr">Culture name</param>
/// <param name="returnUrl">The url to return to after setting the cookie</param>
public IActionResult OnGetSetCultureCookie(string cltr, string returnUrl)
{
    Response.Cookies.Append(
        CookieRequestCultureProvider.DefaultCookieName,
        CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(cltr)),
        new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
    );

    return LocalRedirect(returnUrl);
}

For more details see:

I hope my answer has solvved your issue,
feel free to reopen if needed.