0

I am having problems with my MVC Routes.

I am trying to get to the following url ... "http://localhost/api/Countries"

I have defined the following routes in the following order ...

    RouteTable.Routes.MapHttpRoute(
        name: "Continents",
        routeTemplate: "api/countries/Continents",
        defaults: new { controller = "countries", Action="Continents" }
        );
    RouteTable.Routes.MapHttpRoute(
        name: "CountryRegions",
        routeTemplate: "api/countries/Regions",
        defaults: new { controller = "countries", Action = "CountryRegions" }
        );

    RouteTable.Routes.MapHttpRoute(
        name: "CountryByCodeApi",
        routeTemplate: "api/{controller}/{countryCode}",
        defaults: new { controller="countries", countryCode = System.Web.Http.RouteParameter.Optional }
        );

Whenever I go to the desired URL I am getting the error "Multiple actions were found that match the request". This would make sense if the third segment of the routeTemplate property was optional but it was my understanding that by NOT enclosing it in braces that it made it a required segment in the target URL. Obviously "http://localhost/api/countries" does not include "Continents" or "Regions" so why would they be identified as matching the request.

Ya' know. These routes SEEM like a simple enough thing but when you get down to it it's a cryptic as RegEx's !!!

Any thoughts?

1 Answer 1

1

The last route definition doesn't provide action name through route definition nor it provides it through route defaults. If route definition should omit it, then add it to defaults as this:

routes.MapRoute(
    "CountryByCodeApi",
    "api/{controller}/{countryCode}",
    new {
        controller="countries",
        countryCode = RouteParameter.Optional,
        action = "CountryCodes"
    }
);

Note that this is just the last route definition. The upper couple stays as it is.

public ActionResult CountryCodes(string countryCode)
{
    // do whatever you please
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir! That was indeed the problem!

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.