6

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

谁能告诉我哪里出错了?

全球.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

4

2 回答 2

21

MapHttpRoute路由到继承ApiController.

在您的示例 HomeController 继承了标准Controller(不是 ApiController),您需要使用MapRoute它来找到控制器:

routes.MapRoute(
  name: "HomeDetails",
  url: "Home/Detail/{articleId}/{articleVersion}",
  defaults: new { controller = "Home", action = "Detail", articleId = 0, articleVersion = 0.0 }
);
于 2012-06-01T10:14:05.317 回答
0

嗨,这样的代码更改。

 routes.MapHttpRoute(
      name: "HomeDetails",
      routeTemplate: "{controller}/{action}/{articleId}/{articleVersion}",
      defaults: new { controller = "Home", action = "Detail", articleId = "0", articleVersion = "0.0" }
  );
于 2012-06-01T09:41:40.753 回答