'ASP.NET Core 5 MVC localization query string working but routing not working

In trying to localize my application, the query string localization has worked and accept language header also working, but routing is not working. Here is my code:

Startup.cs

public static IServiceCollection AddLocalizationServices(this IServiceCollection services, IConfiguration _config)
{
    string defaultCulture = _config.GetValue<string>("DefaultCulture");
    services.AddLocalization(options => options.ResourcesPath = "Resources");
    services.Configure<RequestLocalizationOptions>(
        options =>
        {
            var supportedCultures = new[]
            {
                new CultureInfo("en"),
                new CultureInfo("ar")
            };

            options.DefaultRequestCulture = new RequestCulture(culture: defaultCulture, uiCulture: defaultCulture);
            options.SupportedCultures = supportedCultures;
            options.SupportedUICultures = supportedCultures;

            options.RequestCultureProviders.Insert(0, new RouteDataRequestCultureProvider()
            {
                Options = options,
                RouteDataStringKey = "lang",
                UIRouteDataStringKey = "lang"
            });
            options.RequestCultureProviders.Insert(1, new QueryStringRequestCultureProvider());
            //options.RequestCultureProviders.Insert(2, new CookieRequestCultureProvider());
            options.RequestCultureProviders.Insert(3, new AcceptLanguageHeaderRequestCultureProvider());
        });

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

    return services;
}

public static IApplicationBuilder AddLocalizationBuilder(this IApplicationBuilder app)
{
    var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
    app.UseRequestLocalization(locOptions.Value);

    return app;
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalizationServices(_config);

    services.AddControllersWithViews()
        .AddDataAnnotationsLocalization(options =>
        {
            options.DataAnnotationLocalizerProvider = (type, factory) =>
            {
                var assemblyName = new AssemblyName(typeof(ValidationResource).GetTypeInfo().Assembly.FullName);
                return factory.Create("ValidationResource", assemblyName.Name);
            };
        });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        //app.ConfigureExceptionHandler();
    }
    else
    {
        //Global error handling instead of try, catch
        app.ConfigureExceptionHandler();

        //app.UseHsts();
    }

    app.AddLocalizationBuilder();

    //app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    string defaultCulture = _config.GetValue<string>("DefaultCulture");
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{lang:lang}/{controller=Home}/{action=Index}/{id?}");

        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{*catchall}",
            defaults: new { controller = "Home", action = "RedirectToDefaultLanguage", lang = defaultCulture });
    });
}

_ViewImports.cshtml

@using CoreCMS.MVC
@using CoreCMS.Data
@using Microsoft.Extensions.Localization

@inject IStringLocalizer<SharedResource> _loc

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Index.cshtml

@_loc["Title"]

When trying to access website with the following url : http://localhost:14896/en or http://localhost:14896/ar the culture not working but when using this url http://localhost:14896/?culture=ar or http://localhost:14896/?culture=en the culture is working well



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source