ASPNET MVC自定义路由失败,“未找到与名为'Home'的控制器匹配的类型。”

时间:2012-06-01 09:23:33

标签: asp.net-mvc routing

我正在尝试创建一个自定义路由来处理具有多个参数的特定网址。我已经向global.asax添加了一个新的新路由定义但是当我尝试导航到该操作时,我收到错误消息“找不到与名为'Home'的控制器匹配的类型。”

谁能告诉我哪里出错了?

的Global.asax:

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

  routes.MapHttpRoute(
      name: "HomeDetails",
      routeTemplate: "Home/Detail/{articleId}/{articleVersion}",
      defaults: new { controller = "Home", action = "Detail", articleId = "0", articleVersion = "0.0" }
  );

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

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

控制器:

public class HomeController : Controller
{

  public ViewResult Index()
  {
    return View();
  }

  public ViewResult Detail(int articleId, decimal articleVersion)
  {
  // does stuff here...
  return View(model);
  }

}

我试图点击的网址类似于http://localhost/home/detail/1234/1.2

2 个答案:

答案 0 :(得分:21)

MapHttpRoute路由到继承ApiController的Web API控制器。

在您的示例中,HomeController继承标准Controller(不是ApiController),您需要使用MapRoute来代替控制器:

routes.MapRoute(
  name: "HomeDetails",
  url: "Home/Detail/{articleId}/{articleVersion}",
  defaults: new { controller = "Home", action = "Detail", articleId = 0, articleVersion = 0.0 }
);

答案 1 :(得分:0)

你好这样的代码改变。

 routes.MapHttpRoute(
      name: "HomeDetails",
      routeTemplate: "{controller}/{action}/{articleId}/{articleVersion}",
      defaults: new { controller = "Home", action = "Detail", articleId = "0", articleVersion = "0.0" }
  );