0

I have my ASP.NET Core 8 project that references to external project that contains the following controller:

public class AccountController
{
    [HttpGet]
    [AllowAnonymous]
    public async Task<IActionResult> Login(string returnUrl = null)
    {
        // ...
    }

    [HttpGet]
    [AllowAnonymous]
    public async Task<IActionResult> ChangePassword(string returnUrl = null)
    {
        // ...
    }
}

where:

  • AccountController.Login is mapped to route /Login
  • AccountController.ChangePassword is mapped to route /ChangePassword

I would like to replace these routes in Startup.cs of my ASP.NET Core 8 project, so that the routes support multiple cultures as follows:

AccountController.Login -> /en/login, /it/login

AccountController.ChangePassword -> /en/change-password, /it/cambia-password

Could someone provide guidance or an example on how to configure this in Startup.cs file?

2
  • You should consider reading this post and see if it helps. stackoverflow.com/questions/3683404/… You can't necessarily RegisterRoutes as that is .NET Framework, but you can define a default route in Startup.cs and add language as a route parameter: learn.microsoft.com/en-us/aspnet/core/mvc/controllers/… Commented Jul 24, 2024 at 16:50
  • What's your routes configuration in the ASP.NET Core 8 project to access controller methods from the external project? Could you provide the code of it, and the framework of the external project? I want to test it with more specific information. Commented Jul 25, 2024 at 10:33

1 Answer 1

0

To support multiple cultures by changing the routes, you can read about this document: Apply the RouteDataRequest CultureProvider

Below is a sample demo:

In the asp.net core mvc test project:

1.Create the resource file first, refer to Resource files

The name of resource file must match the view page (my test view: Views\Home\Index.cshtml)

resource file

2.Configure in the program.cs:

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

builder.Services.AddMvc()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
    .AddDataAnnotationsLocalization();


builder.Services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new List<CultureInfo>
                {
                    new CultureInfo("en"),
                    new CultureInfo("it")
                    // Add more cultures as needed
                };

    options.DefaultRequestCulture = new RequestCulture("it");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;

    options.RequestCultureProviders = new List<IRequestCultureProvider>
                {
                    new RouteDataRequestCultureProvider()
                    {
                        RouteDataStringKey = "culture",
                        Options = options // This line ensures options.DefaultRequestCulture is used
                    }
                };
});


app.UseRequestLocalization();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "localized-login",
        pattern: "{culture}/{action=Index}",
        defaults: new { controller = "Home", action = "Index" }, // In your code, you should change to `controller = "Account" `
        constraints: new { culture = new RegexRouteConstraint(@"^[a-zA-Z]{2}(-[a-zA-Z]{2})?$") }
    );

    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

In the external project:

3.Inject IStringLocalizer in the Controller:

private readonly IStringLocalizer<HomeController> _localizer;

public HomeController(IStringLocalizer<HomeController> localizer)
{
    _localizer = localizer;
}

public IActionResult Login()
{

    ViewData["Title"] = _localizer["LoginPageTitle"];
    ViewData["ButtonText"] = _localizer["LoginButtonText"];

    return View();
}

4.Inject the IViewLocalizer in the Login view page:

@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer

<h1>@Localizer["LoginPageTitle"]</h1>
<button>@Localizer["LoginButtonText"]</button>

Test result:

it culture test

en culture test

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.