Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Culture in URL required? #15

Closed
morgrowe opened this issue Dec 22, 2020 · 5 comments
Closed

Culture in URL required? #15

morgrowe opened this issue Dec 22, 2020 · 5 comments

Comments

@morgrowe
Copy link

morgrowe commented Dec 22, 2020

Hi Ziya

I'm having a little bit of an issue with culture routing in my application. I've not had this problem before, so I'm wondering if something has changed in XLocalizer, or whether I'm doing something silly again.

Here's my Startup.cs after following Using DB as Localization Source:

public void ConfigureServices(IServiceCollection services)
{
        // stuff 
        services.Configure<RequestLocalizationOptions>(opts =>
        {
            var cultures = new CultureInfo[]
            {
                new CultureInfo("en")
                , new CultureInfo("cy")
            };
        
            opts.SupportedCultures = cultures;
            opts.SupportedUICultures = cultures;
            opts.DefaultRequestCulture = new RequestCulture("en");
            opts.RequestCultureProviders.Insert(0, new RouteSegmentRequestCultureProvider(cultures));
        });
        
        services.AddRazorPages()
            .AddMvcOptions((opts) => {
                opts.Filters.Add(new AuthorizeFilter());
                opts.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
            })
            .AddRazorPagesOptions((ops) => {
                ops.Conventions.Insert(0, new RouteTemplateModelConventionRazorPages());
            })
            .AddXDbLocalizer<DashboardDbContext, DummyTranslator, AppLocalizationResource>((opts) =>
            {
                opts.AutoTranslate = false;
                opts.UseExpressMemoryCache = false;
            });

        // more stuff 
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseRequestLocalization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

If I make a request to /, I recieve the Index page in English--perfect.

If they make a request to /Dashboard (for example), the routing seems to break. Instead of seeing the Dashboard page, I still see Index page. However, if I put /en/Dashboard in the URL manually, the Dashboard page displays as expected.

My understanding was if there is no culture in the URL, the fallback one will be used instead. I read Culture fallback behaviour and that sounds ideal, I just can't seem to get it to work.

Any idea what's going on? Maybe I need to update something in the app.UseEnpoints()?

Thank you
Morgan

@LazZiya
Copy link
Owner

LazZiya commented Dec 23, 2020

Hi Morgan,

The culture fallback behaviour works for the main route that ends with {culture} param even if there is no culture parameter detected in the request, basically the home page route.

But for all other routes like /en/Dashboard/ there must be a culture param in the request, otherwise the route will not match the pattern in the route table and it will break. There could be some work around for such cases like adding a second route pattern without {culture} but this will over complicate the routing table.

So if you want to use route value based localization the best solution is to guarantee the presence of {culture} param in the url to match the relevant route.

Notice:

If the application is using razor pages and controllers the route convention for both must be configured in startup:

.AddMvcOptions((ops) => {
        ...
        ops.Conventions.Insert(0, new RouteTemplateModelConventionMvc());
    })
    .AddRazorPagesOptions((ops) => {
        ops.Conventions.Insert(0, new RouteTemplateModelConventionRazorPages());
    })
    ....

Best regards,
Ziya

@morgrowe
Copy link
Author

Hi Ziya,

Sorry for the delay getting back to you.

Ok that makes sense, thank you. So my understanding is that XLocalizer will only fallback to my default culture if / is the route. It doesn't work for any other route. And because of this, all URLs must start with /{culture}/ in order for the localization to work as expected when using RouteTemplateModelConventionRazorPages and/or RouteTemplateModelConventionMvc. For example /en/Dashboard will work, but /Dashboard will not (as designed).

I think in previous projects I had a route of something like {culture=en}/{controller=Home}/{action=Index}/{id?}, which was causing the behaviour I expected. I'm going to leave it out this time and see how I get on.

Thankfully, I found a nice AnchorTagHelper that, when modified slightly, automatically adds the current culture to the URL. The thought of adding asp-route-culture="@Context.Request.RouteValues["culture"]" to all of my anchor tags was depressing!

Kind regards,
Morgan

@LazZiya
Copy link
Owner

LazZiya commented Dec 24, 2020

I know that taghelper, and I've used a similar approach for a while, but for now I prefer to manually add the asp-route-culture="@CultureInfo.CurrentCulture.Name till dotnet team solves this open issue Hopefully we will see the official solution before retiring :)

Kind regards,
Ziya

@LazZiya
Copy link
Owner

LazZiya commented Dec 24, 2020

Meanwhile, if you don't use RouteSegmentCultureProvider and QueryStringRequestCultureProvider you will have urls free of {culture} param, and the localization will work with CookieRequestCultureProvider depending on culture cookie value.

The downside of this appoarch that it depends on cookies, so if the user has not allowed cookies it will not work properly, additionally you can't share localized URLs.

@morgrowe
Copy link
Author

morgrowe commented Dec 24, 2020

Yes, I stumbled across that issue, too. I like the tag helper approach as it should allow me to just remove the tag helper if/when the official solution is released.

I think, by far, the RouteSegmentCultureProvider is the best solution, so I'll stick with that. I like the ability to send someone a URL with the page already localized. I have a requirement for the localization to be based off the TLD, for example, mywebsite.wales (to be localized in English) or mywebsite.cymru (to be localized in Welsh). I haven't had the chance to look into that yet with XLocalizer, but I'm hoping I'll be able to follow your advice given here for this project. That can wait until next year though. :)

Cheers
Morgan

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants