23

I recently added Microsoft.AspNet.WebApi.WebHost to a MVC WebAPI project which would allow me to use the [Route("api/some-action")] attribute on my action. I solved some errors using this article but can't solve the third error below. Added solved errors below to get feedback if I did anything wrong.

First Error: No action was found on the controller 'X' that matches the name 'some-action'
Solution: Added config.MapHttpAttributeRoutes(); to WebApiConfig.cs Register method.

Second Error: System.InvalidOperationException The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
Solution: Added GlobalConfiguration.Configure(WebApiConfig.Register); to Global.asax.cs Application_Start

Third Error: System.ArgumentException: A route named 'MS_attributerouteWebApi' is already in the route collection. Route names must be unique.
Solution = ?

I've already tried cleaning and deleting all DLLs from bin folder according to this post.

Community
  • 1
  • 1
joym8
  • 4,014
  • 3
  • 50
  • 93

10 Answers10

45

I had a similar problem and it was related to a copy paste error on my part where I added a copy of this line in my WebApiConfig.cs file:

config.MapHttpAttributeRoutes();

make sure you only have one of these.

BraveNewMath
  • 8,090
  • 5
  • 46
  • 51
  • 3
    or like me duplication was in Global.asax.cs with GlobalConfiguration.Configure(config => config.MapHttpAttributeRoutes()) – Iman Apr 09 '17 at 05:26
18

In the Global.asax, check how many times WebApiConfig.Register function has been called.

JoeyZhao
  • 514
  • 5
  • 12
7

Solved! Removed the line WebApiConfig.Register(GlobalConfiguration.Configuration); from Global.asax.cs Application_Start.

joym8
  • 4,014
  • 3
  • 50
  • 93
7

I have solved by cleaning the deployment directory before copy the new files. Probably there was some old file that try to register the same root multiple times.

Davide Icardi
  • 11,919
  • 8
  • 56
  • 77
3

I had the same issue and I discovered that in WebApiConfig.cs and after I added configuration for API version

I have those two lines

config.MapHttpAttributeRoutes(constraintResolver);

config.MapHttpAttributeRoutes();

I removed the second line

the final code is

 public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

        // Web API routes
        var constraintResolver = new DefaultInlineConstraintResolver()
        {
            ConstraintMap =
            {
                ["apiVersion"] = typeof( ApiVersionRouteConstraint )
            }
        };
        config.MapHttpAttributeRoutes(constraintResolver);
        config.AddApiVersioning();

        // Web API configuration and services

        // Web API routes
       // config.MapHttpAttributeRoutes();

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


    }
}
Mohamed Salah
  • 160
  • 1
  • 5
2

For anybody stumbling across this as I did, this error will happen if you rename the Assembly name (project properties). In my case I was renaming a project, and went into the properties to change the assembly name (which VS2013 won't do for you).

Because the assembly name is different, a Clean or Rebuild will not remove the "old" assembly if it is in the \bin folder. You have to delete the assembly from the \bin folder, then rebuild & run.

VictorySaber
  • 3,084
  • 1
  • 27
  • 45
2

Probably you have same register more than one.

Try to delete below codes from Global.asax:

GlobalConfiguration.Configure(WebApiConfig.Register);
  RouteConfig.RegisterRoutes(RouteTable.Routes);

and write this ones instead of them :

GlobalConfiguration.Configuration.EnsureInitialized(); BundleConfig.RegisterBundles(BundleTable.Bundles);

I am not sure about reason; but it worked for me in my same case.

nzrytmn
  • 6,193
  • 1
  • 41
  • 38
0

I was also experiencing a similar problem (not the MS_attributerouteWebApi route in particular, but a different named route). After verifying only one config.MapHttpAttributeRoutes() existed, began realizing that MapHttpAttributeRoutes will register all project assemblies including externally referenced ones. After finding out that I had a referenced assembly that was registering its own routes, I found a way to exclude or "skip over" routes by overriding the DefaultDirectRouteProvider:

/// <summary>
/// Allows for exclusion from attribute routing of controllers based on name
/// </summary>
public class ExcludeByControllerNameRouteProvider : DefaultDirectRouteProvider {

    private string _exclude;
    /// <summary>
    /// Pass in the string value that you want to exclude, matches on "ControllerType.FullName" and "ControllerType.BaseType.FullName"
    /// </summary>
    /// <param name="exclude"></param>
    public ExcludeByControllerNameRouteProvider(string exclude) {
        _exclude = exclude;
    }

    protected override IReadOnlyList<RouteEntry> GetActionDirectRoutes(
    HttpActionDescriptor actionDescriptor,
    IReadOnlyList<IDirectRouteFactory> factories,
    IInlineConstraintResolver constraintResolver)
    {
        var actionRoutes = new List<RouteEntry>();
        var currentController = actionDescriptor.ControllerDescriptor.ControllerType;
        if (!currentController.FullName.Contains(_exclude) && !currentController.BaseType.FullName.Contains(_exclude))
        {
            var result = base.GetActionDirectRoutes(actionDescriptor, factories, constraintResolver);
            actionRoutes = new List<RouteEntry>(result);
        }
        return actionRoutes.AsReadOnly();
    }
}

This allows for you to pass a Controller name or Base Type name in to exclude in your WebApiConfig.cs like:

config.MapHttpAttributeRoutes(new ExcludeByControllerNameRouteProvider("Controller.Name"));

Whether or not directly related, hoping this snippet can help!

vandsh
  • 1,329
  • 15
  • 12
0

I was experiencing the same problem. The solution I found was that I needed visual basic support for mono. When I executed "yum install mono-basic" and restarted my computer the error went away.

DonM
  • 1
  • 1
0

In my case error was : "A route named 'MS_attributerouteWebApi' is already in the route collection. Route names must be unique. Parameter name: name"

Code was:

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            config.MapHttpAttributeRoutes();  // this line had issue

            var constraintResolver = new DefaultInlineConstraintResolver();
            constraintResolver.ConstraintMap.Add("nonzero", typeof(NonZeroConstraint));
            config.MapHttpAttributeRoutes(constraintResolver);

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

Solution : I just removed - config.MapHttpAttributeRoutes(); line from above method and it got resolved.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103