AspNetCore.Mvc.Routing.Localization

Build Nuget

Summary

The package AspNetCore.Mvc.Routing.Localization helps you create localized routes. Your routes can be specific per language - en-US/Products and cs-CZ/Produkty, which call the same route.

Supported combinations:

Status Controller Action
Supported LocalizedRouteAttribute LocalizedRouteAttribute
Supported LocalizedRouteAttribute RouteAttribute
Supported LocalizedRouteAttribute Action
Supported RouteAttribute LocalizedRouteAttribute
Supported Controller LocalizedRouteAttribute

You can see localized routes here - {culture}/LocalizedRoutes/Index.

Setup

WARNING: We support only the RouteDataRequestCultureProvider with the RouteDataStringKey = "culture".

Register the services into the IServiceCollection.

var supportedCultures = new[]
{
    new CultureInfo("cs-CZ"),
    new CultureInfo("en-US"),
};
services.AddLocalizedRouting(supportedCultures);

Implement and register the DynamicRouteValueTransformer.

public class LocalizedRoutingTranslationTransformer : DynamicRouteValueTransformer
{
    private ILocalizedRoutingDynamicRouteValueResolver _localizedRoutingDynamicRouteValueResolver;
    
    public LocalizedRoutingTranslationTransformer(ILocalizedRoutingDynamicRouteValueResolver localizedRoutingDynamicRouteValueResolver)
    {
        _localizedRoutingDynamicRouteValueResolver = localizedRoutingDynamicRouteValueResolver;
    }
    
    public override async ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
    {
        return await _localizedRoutingDynamicRouteValueResolver.ResolveAsync(values);
    }
}
services.AddSingleton<LocalizedRoutingTranslationTransformer>();

Register your implementation of the DynamicRouteValueTransformer into the endpoints middleware with the following template.

app.UseEndpoints(endpoints =>
{
    endpoints.MapDynamicControllerRoute<LocalizedRoutingTranslationTransformer>("{culture=en-US}/{controller=Home}/{action=Index}/{id?}");
    endpoints.MapControllerRoute(name: "default", pattern: "{culture=en-US}/{controller=Home}/{action=Index}/{id?}");
});

Set up the localized routing middlewares.

var supportedCultures = new[]
{
    new CultureInfo("cs-CZ"),
    new CultureInfo("en-US"),
};
app.UseLocalizedRouting("en-US", supportedCultures);

Register the tag helper from the AspNetCore.Mvc.Routing.Localization package into the _ViewImports.cshtml file, which offers to you localize your routes in a Views.

@addTagHelper *, AspNetCore.Mvc.Routing.Localization