【问题标题】:Controller cannot be found找不到控制器
【发布时间】:2014-06-05 22:20:43
【问题描述】:

我正在开发一个 ASP.NET MVC 4 站点。我在 Controllers 文件夹中有一个 ArtistController。

ArtistController 有一个 Get 方法:

public ActionResult Get(string paramOne, string paramTwo)

在 RouteConfig.cs 我有这条路线,在默认路线之前:

routes.MapRoute(
            name: "artistApi",
            url: "api/artist/{action}/{id}",
            defaults: new { controller = "Artist", action = "Get", id = UrlParameter.Optional }
            );

当我尝试测试这个调用时,我得到:

未找到与请求 URI 匹配的 HTTP 资源。找不到与名为“艺术家”的控制器匹配的类型。

如果我从路由中删除 api 部分,它会起作用:

url: "artist/{action}/{id}"

我没有使用 WebApi,只是一个普通的 Controller。

知道为什么这条路线找不到控制器吗?

谢谢!

【问题讨论】:

  • 测试 URL 是什么样的?
  • 网址如下所示:api/Artist/Albums?paramOne=ArtistName&paramTwo=otherValue
  • 我已将 url 值更改为“test/artist/{action}”,现在它正在工作。在我看来,您只能使用 Web API 使用“api/controller”。对此有什么想法吗?

标签: c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing


【解决方案1】:

确保您的 App_Start 文件夹中没有 WebApiConfig.cs 文件。这可能会覆盖您的路由定义。

【讨论】:

  • 是的,这就是问题所在。我卸载了 Web API,它工作正常。谢谢!
【解决方案2】:

如果我理解正确的话,

url: "api/artist/{action}/{id}" 行将 id 作为查询字符串

例如 www.yourwebsite/youractioncontroller/1

你的 actionResult 需要两个 MVC 不知道该怎么做的查询字符串

还有一件事是“艺术家”需要成为您的控制器,这通常是 {控制器}

或者你的艺术家控制器应该是艺术家控制器

【讨论】:

  • 听起来很合理......但我有这个网址:api/Artist/Albums?paramOne=ArtistName&paramTwo=otherValue,我怎样才能创建接受这个的路线?
  • 可能类似于 {controller}/{action}/{paramOne}/{paramTwo}/
【解决方案3】:

很可能您的路线没有正确排序 - 如果api/ 在您更具体的路线之前,它将首先匹配并且永远不会到达您的新路线。

// More specific routes should go before generic ones:
routes.MapRoute(
        name: "artistApi",
        url: "api/artist/{action}/{id}",...);
routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

【讨论】:

  • 不,路线排序正确。这不是问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多