How to use RouteDataRequestCultureProvider with ASP.NET Core 2.2 EndpointRouting enabled?
Asked Answered
H

1

14

I am trying to use the RouteDataRequestCultureProvider in a new ASP.NET Core 2.2 MVC project.

I've read the Microsoft documentation on Routing in ASP.NET Core to understand the changes introduced in 2.2, but I don't understand why "culture" isn't recognized as an ambient value for URL generation.

I updated ConfigureServices in Startup.cs to include the settings:

var supportedCultres = new[] { new CultureInfo("en"), new CultureInfo("fr") };
services.Configure<RequestLocalizationOptions>(options =>
{
    options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en");
    options.SupportedCultures = supportedCultres;
    options.SupportedUICultures = supportedCultres;
    options.RequestCultureProviders = new[] { new RouteDataRequestCultureProvider { Options = options } };
});

And I modified the app and default route in Configure to use a "culture" path segment:

var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value;
app.UseRequestLocalization(locOptions);
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{culture:regex(^(en|fr)$)}/{controller=Home}/{action=Index}/{id?}");
});

This route will resolve to HomeController.Index() when I navigate to either /en or /fr as expected, but any links to other actions with the Anchor Tag Helper will render as <a href=""> (including the Privacy link generated by the scaffold).

Turning off EnableEndpointRouting causes the Anchor Tag Helper to work again:

services.AddMvc(opts => { opts.EnableEndpointRouting = false; })
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

Adding an explicit asp-route-culture value also works:

<a asp-route-culture="en" asp-controller="Home" asp-action="About">About</a>

But I don't understand why either change is required since the "culture" route value is already present in the RouteData.Values collection and was automatically used by the anchor tag helper with the previous routing model. These are valid routes to actions, so why is the URL generation failing when the route includes a culture?

Hartzel answered 24/1, 2019 at 17:52 Comment(2)
Did you manage to resolve this?Indispensable
im having the same issue in core 3.1 - #59268471Getty
G
0

I had the same issue with net core 3.1. I eventually managed to discover the cause and find a solution.

read my solution here - https://mcmap.net/q/902671/-using-routedatarequestcultureprovider-in-asp-net-core-3-1/59283426#59283426

TLDNR: since core 2.2 ambient route values are no longer passed into the url builder, you need to explicitly pass them in. I solved it by extending the razor anchor tag helper.

Getty answered 11/12, 2019 at 16:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.