Search code examples
c#localizationasp.net-core-mvcasp.net-mvc-routing

ASP.NET Core 3 MVC endpoint routing and localization by route


I started messing with endpoint routing and url translation but i think i'm missing somthing.

My solution is here

I started from the example in this blog post

writing urls in address bar works as expected but I noticed that anchor tag don't generate url at all.

Layout sample

     @{ 
         Dictionary<string, string> routePol = new Dictionary<string, string>();
         routePol.Add("language", "pl");
         routePol.Add("controller", "Home");
         routePol.Add("action", "Index");
    }
    <a asp-all-route-data="routePol">Poland</a>

should generate

<a href="test/pl/Home/Index">Poland<a>

result

<a href >Poland<a>

Main endpoint

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDynamicControllerRoute<TranslationTransformer>(
                    "{language=pl}/{controller=orders}/{action=list}");
            });

I don't understand what is wrong. I read around that with endpoint routing, anchor tag does not generate urls when the provided values generate a not existing route, but the route above should be valid.

If it's possible, is there a way to debug how route is validated or log errors?

EDIT: problem now solved, thanks to Rena. I updated my solution with fixes and I added a useful component for culture change using route value, hope that will be useful to everyone that will stumble in same problems as me.


Solution

  • The blog show us how to translate the url when you send request.But in your case,you just want to render url,it should add route template to match it.

    Here is a smiple workaround like below:

    1.View:

    @{
    Dictionary<string, string> routePol = new Dictionary<string, string>();
    routePol.Add("language", "pl");
    routePol.Add("controller", "zamowienia");
    routePol.Add("action", "lista");    
    }
    @*controler name and action name should be the key name in TranslationDatabase 
    not the value name.*@
    <a asp-all-route-data="routePol">Poland</a>
    

    2.Startup.cs:

    app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{language=pl}/{controller=orders}/{action=list}");
                endpoints.MapDynamicControllerRoute<TranslationTransformer>(
                    "{language=pl}/{controller=orders}/{action=list}");
    
            });
    

    It would generate the url:/pl/zamowienia/lista and when you click the link,it would get into orders/list action