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.

2
  • Optional parameters are suppose to be the last thing in the route template. It wont work when there is anything after the optional parameter. Commented Jun 9, 2016 at 11:08
  • You might want to take a look at this answer 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. Commented Jun 9, 2016 at 16:32

1 Answer 1

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" }
);
Sign up to request clarification or add additional context in comments.

2 Comments

@Nikosi, so there is no way to achieve this without duplicate routes?
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 - stackoverflow.com/a/32839796/5233410

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.