A route named 'DefaultApi' is already in the route collection

Viewed 17781

This question may seems duplicate but this is slightly different. In all other question in SO I had noticed that they have multiple routes registered. but in my case I have just one route.

I am creating asp.net webapi (framework 4.5) and have just one route in RegisterRoutes() method -

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "DefaultApi",
            url: "rest/{controller}/{id}",
            defaults: new { id = UrlParameter.Optional }
        );

    }

Then why is it throwing error?

A route named 'DefaultApi' is already in the route collection. Route names must be unique. Parameter name: name
5 Answers

Fine, I resolved it based on the reply by user3038092. Instead of adding it in the route collection, I added it in HttpConfiguration

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "rest/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

And it worked.

If you are using MVC4 or MVC5 application. Then put your Route Configuration in

WebApiConfig.cs and

also check route name should be unique in both files i.e RouteConfig.cs and WebApiConfig.cs

I see that you call the controller but you do not give the controller name like this:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "DefaultApi",
            url: "rest/{controller}/{id}",
            defaults: new { controller="Home",action="Index",id = UrlParameter.Optional }
        );

    }

that means you regist HomeContrller for the Index view,

Related