Search code examples
asp.net-mvcasp.net-mvc-4url-routingasp.net-mvc-routing

MVC Custom Attribute routing with City and Country URL


I want to create custom attribute routing in MVC, where I want my URLs like this :

www.domain.com/in/best-restaurants-in-india    // FOR COUNTRY INDIA

and

www.domain.com/in/best-restaurants-in-new-delhi-india  // for COUNTRY INDIA CITY DELHI

For this I tried to use this

  [Route("{isocountry}/best-restaurants-in-{country}")]
  [Route("{isocountry}/best-restaurants-in-{city}-{country}")]

But this gives an ambiguous routing issue

I know this is possible as I have seen other website using same in php, but don't know how to do this is MVC.

Please give the proper idea of implementing this ?


Solution

  • you get the error because when you enter

    www.domain.com/in/best-restaurants-in-india
    

    it matches the route in-{country} and you enter

    www.domain.com/in/best-restaurants-in-new-delhi-india
    

    it matches both routs because delhi-india is a string and can be both which makes it ambitious.

    you can achieve this by applying the Order in the route attribute because your routing should be defined from most specific to most generic so your route should be like this

     [Route("{isocountry}/best-restaurants-in-{country}",Order = 2)]
     [Route("{isocountry}/best-restaurants-in-{city}-{country}",Order = 1)]
    

    first it will check the specific route and then the generically defined route.