名为"DefaultApi"的路径已在路径集合中

Ani*_*ani 7 c# asp.net asp.net-web-api asp.net-web-api-routing

这个问题可能看似重复,但这有点不同.在SO的所有其他问题中,我注意到他们注册了多条路线.但就我而言,我只有一条路线.

我正在创建asp.net webapi(框架4.5)并且在RegisterRoutes()方法中只有一个路由 -

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

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

    }
Run Code Online (Sandbox Code Playgroud)

那为什么会抛出错误?

A route named 'DefaultApi' is already in the route collection. Route names must be unique. Parameter name: name
Run Code Online (Sandbox Code Playgroud)

Bar*_*art 22

我在添加路线方面遇到了类似的问题DefaultApi.虽然我的ArgumentException堆栈跟踪中的确切"附加详细信息"消息是:

A route named 'MS_attributerouteWebApi' is already in the route collection.
Route names must be unique.
Run Code Online (Sandbox Code Playgroud)

我当然确定我只添加了DefaultApi一次路线,但最后注意到在我Global.asaxApplication_Start方法中我调用了WebApiConfig.Register(..)两次,虽然在下面 - 不是立即明显 - 方式:

WebApiConfig.Register(GlobalConfiguration.Configuration);
GlobalConfiguration.Configure(WebApiConfig.Register);
Run Code Online (Sandbox Code Playgroud)

另一个严重的'copypasterites'案例!我只是删除了这WebApiConfig.Register(..)条线,这解决了我的问题.

(我使用的是WEB API 2.0/.NET 5)


小智 9

原因:重命名命名空间而不删除关联的bin和输出文件.

SOLUTION:手动删除输出目录中的binobj文件夹.(清理解决方案是不够的,一些有问题的残留文件仍然会导致此问题.)

......无论如何,那是我的经历.


Ani*_*ani 3

好的,我根据用户3038092的回复解决了。我没有将其添加到路由集合中,而是将其添加到 HttpConfiguration 中

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

它奏效了。