Search code examples
c#asp.net-mvcasp.net-mvc-5asp.net-mvc-routing

Asp.net MVC5 route parameter issue


I am trying to create URLs in asp.net MVC5. The behavior I'm look for is below:

http://www.example.com/es/faqs ----> when language is Spanish
http://www.example.com/faqs    ----> when language is english

My route for this URL:

routes.MapRoute(
        name: "FAQs",
        url: "{lang}/FAQs",
        defaults: new { controller = "StaticPages", action = "FAQs", lang= UrlParameter.Optional }
    );

This URL renders find in Spanish --> http://www.example.com/es/faqs

But my issue is that this url does not function correctly --> http://www.example.com/faqs

When I attempt to visit this URL I get a page not found error.

In my route, I am trying to make lang(Language code) optional, why doesn't my route work when have no language code in the URL.


Solution

  • Optional parameters are suppose to be the last thing in the route template. It wont work when there is anything after the optional parameter. You are goin to have to create two templates to allow for the two formats

    routes.MapRoute(
            name: "LocalizedFAQs",
            url: "{lang}/FAQs",
            defaults: new { controller = "StaticPages", action = "FAQs", lang = "en" }
    );
    
    routes.MapRoute(
            name: "DefaultFAQs",
            url: "FAQs",
            defaults: new { controller = "StaticPages", action = "FAQs", lang = "en" }
    );