102

I'm doing an ASP.NET MVC 3 web service and I keep getting this exception intermittently.

Stack trace:

Server Error in '/' Application.

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

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ArgumentException: A route named 'ListTables' is already in the route collection. Route names must be unique.
Parameter name: name

Source Error: 


Line 24:            //     }
Line 25:            // );
Line 26:             context.MapRoute(
Line 27:                 "ListTables",
Line 28:                 // example: 

Source File: C:\inetpub\wwwroot\SchemaBrowserService\Website\Areas\Api\ApiAreaRegistration.cs    Line: 26 

Stack Trace: 


[ArgumentException: A route named 'ListTables' is already in the route collection. Route names must be unique.
Parameter name: name]
   System.Web.Routing.RouteCollection.Add(String name, RouteBase item) +2329682
   System.Web.Mvc.RouteCollectionExtensions.MapRoute(RouteCollection routes, String name, String url, Object defaults, Object constraints, String[] namespaces) +236
   System.Web.Mvc.AreaRegistrationContext.MapRoute(String name, String url, Object defaults, Object constraints, String[] namespaces) +59
   System.Web.Mvc.AreaRegistrationContext.MapRoute(String name, String url, Object defaults) +17
   SchemaBrowserService.Areas.Api.ApiAreaRegistration.RegisterArea(AreaRegistrationContext context) in C:\inetpub\wwwroot\SchemaBrowserService\Website\Areas\Api\ApiAreaRegistration.cs:26
   System.Web.Mvc.AreaRegistration.CreateContextAndRegister(RouteCollection routes, Object state) +105
   System.Web.Mvc.AreaRegistration.RegisterAllAreas(RouteCollection routes, IBuildManager buildManager, Object state) +199
   System.Web.Mvc.AreaRegistration.RegisterAllAreas(Object state) +45
   System.Web.Mvc.AreaRegistration.RegisterAllAreas() +6
   Website.MvcApplication.Application_Start() in C:\Users\djackson\Downloads\RestApiMvc3\Website\Website\Global.asax.cs:35

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272

It's probably related to the fact that Route Debugger shows that I have some old routes that I've modified or deleted and won't go away (even after rebooting my machine). The stack trace also refers to a source file that has long since been deleted and my app has been moved to a new location, cleaned and rebuilt since then. What am I missing?

Here is all of my route registration code:

// in Global.asax.cs:
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        "Default2", // Route name
        "Api/{controller}/{action}/{id}", // URL with parameters
        new { controller = "DataSource", action = "Index", area = "Api", id = UrlParameter.Optional } // Parameter defaults
        );

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    }

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterRoutes(RouteTable.Routes);
}

// in ApiAreaRegistration.cs:
public class ApiAreaRegistration : AreaRegistration
{
    public override string AreaName { get { return "Api"; } }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        // DataSources

        // Tables
        context.MapRoute(
            "ListTables",
            // example: 
            // /api/DataSources/DataSource/1/schemata/schema/dbo/tables
               "Api/DataSources/DataSource/{dataSourceId}/schemata/{schemaName}/tables",
            new
            {
                controller = "Tables",
                action = "TableList",
                schemaName = "dbo",
                dataSourceId = "DefaultId"
            }
        );


        // Schemata
        context.MapRoute(
          "Schema",
            // example: 
            // /api/DataSources/DataSource/1/schemata/schema/dbo
              "Api/DataSources/DataSource/{dataSourceId}/schemata/{schemaName}",
          new
          {
              controller = "Schema",
              action = "Schema",
              dataSourceId = "DefaultId",
              schemaName = UrlParameter.Optional
          }
       );

       // // DataSources
        context.MapRoute(
            "SingleDataSource",
            "Api/DataSources/DataSource/{dataSourceId}",
            new
            {
                controller = "DataSource",
                action = "DataSource",
                dataSourceId = UrlParameter.Optional
            }
        );
        context.MapRoute(
            "ListDataSources",
            "Api/DataSources",
            new
            {
                controller = "DataSource",
                action = "DataSourceList",
                dataSourceId = "DefaultId"
            }
        );
        context.MapRoute(
             "Api_default",
             "Api/{controller}/{action}/{id}",
             new { action = "Index", id = UrlParameter.Optional }
        );

    }
}
Rn222
  • 2,167
  • 2
  • 20
  • 36

16 Answers16

306

To fix this problem I had to go into the bin folder on my project, delete all DLL files and then rebuild and this fixed the problem.

Flea
  • 11,176
  • 6
  • 72
  • 83
  • 11
    Simply cleaning the solution we do the same thing. – Fabio Milheiro Aug 19 '12 at 12:31
  • 85
    @Bomboca - cleaning doesn't delete DLLs that aren't part of the project. E.g. if you changed your project's assembly name, the old assembly would remain in the `bin` folder. – Josh M. Mar 30 '13 at 05:14
  • 2
    I was experiencing the same issue and this solved my problem immediately. Thank you! – Aluan Haddad Feb 11 '14 at 04:19
  • 1
    Renamed my project, and the old DLL was still in the bin folder. Please people: permanent solution, when PUBLISHING, delete all files in target directory first! (option when publishing to directory) – Stijn Sep 30 '14 at 15:11
  • 1
    I had the same issue when deploying via Web Deploy to Azure Websites (site worked locally). This lead to the solution, I had renamed the assemblies but "Remove additional files at destination" was unchecked so they were still on the server too. – htuomola Jan 13 '15 at 06:45
  • 1
    This solution resolved the same problem for me in MVC5. – Xipooo Dec 22 '15 at 14:54
  • 2
    I don't know why but "Clean solution" doesn't work for me. Your solution works. – user2980426 May 06 '16 at 18:50
  • 1
    I had the same issue, Clean Solution doesn't work if you rename your files, folders or move objects about it seems to lose track of the bin and obj folders. Using Windows Explorer I had to search in the project folder for any bin and obj items then manually (carefully) delete these folders and do a Build > Rebuild – Trevor Jan 13 '17 at 02:59
  • 1
    I had a similar problem publishing to an Azure Web App. The issue was that a previous deployment to the same site from a different project was causing failures. I opened a console in azure, removed all files in the directory and restarted the site. Once restarted, I published again and this time it all worked. – nmishr Dec 07 '17 at 16:03
  • Also make sure to remove any multiple AreaRegistration.RegisterAllAreas(). – Martin S Ek Jan 02 '18 at 09:41
21

This error can occur due to multiple causes, I had the same error and solved it by modifying the Global.asax class.

The Application_Start method at Global.asax.cs was like:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

The following line occurs twice in this method:

RouteConfig.RegisterRoutes(RouteTable.Routes);

This ensured that the route was twice added to the route list and at the same time causing the error.

I changed the Application_Start method as follows and the error disappeared:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

This may not be the answer for your problem, but can perhaps help others in the future. I didn't see this answer between the others, so I decided to add this.

Max
  • 12,622
  • 16
  • 73
  • 101
  • 2
    There's a duplicate call to AreaRegistration.RegisterAllAreas() too. – Spivonious Sep 25 '15 at 14:00
  • Also, I ran into this: WebApiConfig.Register(GlobalConfiguration.Configuration); with GlobalConfiguration.Configure(WebApiConfig.Register); both calling the same method in WebApiConfig.cs. Trick is of course to put a break where the route name is being set and look at the call stack. – Reid Mar 28 '17 at 02:39
  • I was getting this error and none of the other solutions worked for me, but then I found duplicate AreaRegistration.RegisterAllAreas(); lines in my global.asax file. Removing one of them removed the error. – ewomack Oct 02 '19 at 14:51
11

I found out that Global.asax was referring to an old version of the site's DLL file before I renamed it. The DLL was not being cleaned up when I did Build > Clean up because the VS project/solution didn't refer to it any more. It seems that sometimes only the newer version of the DLL was being used, allowing the site to work correctly, but eventually both of them would be loaded causing the route conflicts.

Rn222
  • 2,167
  • 2
  • 20
  • 36
  • deleting bin and obj worked for me after renaming my project. – Steve Feb 25 '14 at 01:17
  • 3
    How did you find out the Global.asax was referring to an old DLL? – xaisoft Jan 26 '15 at 17:38
  • @xiasoft: The old DLL contained routes that I had deleted but Route Debugger showed that they were still there. When I deleted the old DLL the old routes were also removed. – Rn222 Sep 12 '16 at 17:27
5

The routes get loaded from all assemblies within AppDomain.CurrentDomain, so if your old assemblies are still part of that, you might be still getting old/duplicate routes.

Filip W
  • 27,097
  • 6
  • 95
  • 82
  • 3
    How could I check to see if this is the problem? – Rn222 Jun 11 '12 at 21:21
  • That's right. It happend on my project. When I changed it's name, occured this error. After remove old assembly, the error has gone. – bafsar Apr 17 '17 at 01:01
3

In my case, I faced with this issue, when I added reference to another project from solution, which also was MVC and use the same names in area (I didn't want to added this project, I don't know how it happened). When I removed this DLL, project started to work.

DreamEvil
  • 169
  • 1
  • 13
  • It hadn't even occurred to me that this could happen, since I've always kept my site projects self-contained instead of splitting things into a dozen pieces "because architecture". New team, new conventions, new chances to internalize some of the options I hadn't found useful yet. – brichins Jan 12 '18 at 19:07
2

Deleting the DLLs alone didn't work for me (in VS2013), but deleting the entire 'bin' and 'obj' folders and then building the solution worked perfectly! Makes me wish I hadn't spent so long trying to fix it...

Lyall
  • 1,367
  • 3
  • 17
  • 42
2

None of the suggestions worked for me. Went ahead and restarted the web server (IIS in this case) and that cleared the error after I had fixed the code. DLL must have been cached in IIS.

joel1618
  • 353
  • 4
  • 11
1

try this code, only change name

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
        routes.MapHttpRoute(
          name: "API",
          routeTemplate: "api/{controller}/{action}",
          defaults: new { action = "GetAgentId" }
      );
slfan
  • 8,950
  • 115
  • 65
  • 78
0

I am getting same error. But finally I have got solution. Scenario: I am adding different(mvc4 application) dll in my web api mvc4 application. When try to run. I am getting same error. Root Cause- When my web api application run .Application register all area from self and start loading to current application domain dll references. When application load dll(MVC4 application) that time getting error because current maproute already add key for "HelpPage_Default".

Solution. 1.Change key for RegisterArea in maproute either current application or existing application(Refer dll). 2.Move code dll(mvc4 application) code to different liberary and refer to new dll.

0

I was manually calling AttributeRoutingHttpConfig.Start() in my Global.asax. Did not notice this auto-generated line at the top of the file which automatically calls it.

[assembly: WebActivator.PreApplicationStartMethod(typeof(Mev.Events.Web.AttributeRoutingHttpConfig), "Start")]
Despertar
  • 21,627
  • 11
  • 81
  • 79
0

I had an application that was a Forms app migrated to MVC with a third party component used for authentication which redirected to another site. The component would start a session twice if the user wasn't already logged in (once for initial connection to site and once for return). So I solved this with the following code:

if (routes.Count < 3)
            {
                routes.IgnoreRoute("login.aspx");
                routes.IgnoreRoute("default.aspx");
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new {action = "Index", id = UrlParameter.Optional}
                    );
            }
done_merson
  • 2,800
  • 2
  • 22
  • 30
0

Deleting the dlls in the bin folder did work 100%, I still had dlls my project needed to rebuild. Rather make a copy of the bin folder. then delete the original.rebuild the project. if it fails, place the missing dlls into the bin folder.

0

I was running an old MVC2 website and I got this issue because the IIS 'Managed Pipeline Mode' was set on 'Integrated' by default (press F4 on the project). Changing it to 'Classic' fixed the issue

Phate01
  • 2,499
  • 2
  • 30
  • 55
0

When publishing to an Azure App Service I had to check the Publish Dialog's "Settings"->"File Publish Options"->"Remove additional files at destination" to get the old project DLL and symbol files removed. Then the site would load.

This is essentially the current answers (Fleas's) solution at the core. Delete the offending DLL.

What caused this old DLL to be retained was I was loading an older version of the website (MVC 3~5 templates but different web project with colliding namespaces, since the newer version was a copy of this project made some point in the recent past.) The newer project's DLLs just needed to be deleted. There are various ways to achieve this. I found using a dialog to be the easiest atm. Logging into the file system and axing the files by hand certainly works too.

Hunter-Orionnoir
  • 2,015
  • 1
  • 18
  • 23
0

If you are versioning, and you use two APIs with the same name, you will get this error. If you need the same Get, try changing the Name attribute of the route:

TestsController.cs:

      [MapToApiVersion("1.0")]
      [Route("{moniker}", Name = "GetTest")]
      public async Task<IHttpActionResult> Get(string moniker, bool param1 = false)

  [MapToApiVersion("1.1")]
  [Route("{moniker}", Name = "GetTest11")] // Change name here for a different version
  public async Task<IHttpActionResult> Get(string moniker)

And pass in the version in the URL:

http://localhost:6600/api/tests/2020?api-version=1.1

live-love
  • 48,840
  • 22
  • 240
  • 204
0

faced this issue. the problem was occurred after adding an area to my project. there was a call for MapMvcAttributeRoutes() in RegisterArea() method. therefore, you should not look for a duplicate route names, just look for duplicate MapMvcAttributeRoutes() calls.