1

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.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • Optional parameters are suppose to be the last thing in the route template. It wont work when there is anything after the optional parameter. – Nkosi Jun 09 '16 at 11:08
  • You might want to take a look at [this answer](http://stackoverflow.com/a/32839796/181087) for how to manage the default language. It is also possible to use a decorator pattern on the `Route` class and/or use customized attribute routing so you don't need to duplicate every route. – NightOwl888 Jun 09 '16 at 16:32

1 Answers1

1

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" }
);
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • @Nikosi, so there is no way to achieve this without duplicate routes? – Rishu Sharma Jun 09 '16 at 11:19
  • Not to my knowledge. From a lot of the examples I have seen once you have an optional parameter in the route you can't have anything after it. Take a look at this similar Q&A - http://stackoverflow.com/a/32839796/5233410 – Nkosi Jun 09 '16 at 11:24