0

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?

1 Answer 1

0

You could try as below:

    app.MapControllerRoute(
    name: "default",
    pattern: "{lang=en-us}/{controller=Test1}/{action=HelloAct}");

    app.MapControllerRoute(
    name: "another",
    pattern: "{controller}/{action}/{lang=en-us}");

sections like {lang=en-us}/{controller=Test1}/{action=HelloAct} will perform as below:

Next, the accepted values can be used to expand the route template. The route template is processed:

From left-to-right. Each parameter has its accepted value substituted. With the following special cases: If the accepted values is missing a value and the parameter has a default value, the default value is used.

If the accepted values is missing a value and the parameter is optional, processing continues. If any route parameter to the right of a missing optional parameter has a value, the operation fails. Contiguous default-valued parameters and optional parameters are collapsed where possible.

Check this part of document carefully

with the first partten, you could access your target action with:

"/" or "/en-us" or "/en-us/Test1" or "/en-us/Test1/hellowAction"

but when you try with "/Test1/hellowAction",in fact,it would go to "/Test1/HellowAction/HellowAction"

What i've tried : enter image description here

enter image description here

enter image description here

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.