jeudi 23 février 2023

How to modify routing pattern before {controller} to handle multiple languages in ASP.NET Core

In ASP.NET core, I created a simple Controller and Action with the default routing

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


public class Test1Controller:Controller
{
    public string HelloAct()
    {
        return "Hello World.";
    }
}

https://localhost:port/Test1/HelloAct It is OK, shows "Hello World."

I want to handle multiple languages with URL like Microsoft web site.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-7.0 https://learn.microsoft.com/ja-jp/aspnet/core/fundamentals/routing?view=aspnetcore-7.0 https://learn.microsoft.com/ko-kr/aspnet/core/fundamentals/routing?view=aspnetcore-7.0

Add language name after domain, if the parameter is omitted, I wish it will go to "en-us".

I tried below, modified routing pattern:

app.MapControllerRoute(
    name: "default",
    pattern: "{lang=en-us}/{controller=Home}/{action=Index}/{id?}" });

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

Input: https://localhost:port/Test1/HelloAct but neither is right. Returns 404 not found.

How to modify the routing pattern?

Aucun commentaire:

Enregistrer un commentaire