MVC操作导致404“未找到与控制器匹配的类型”调用控制器工作的默认操作

时间:2014-09-10 18:58:36

标签: asp.net asp.net-mvc-5

我继承了一些ASP.Net MVC代码,我的任务是添加一些新功能。我是一个使用ASP.Net MVC的初学者,主要使用Web Forms。

我添加了一个新的控制器(ApiController),并添加了以下操作:

    // GET: /Api/Index
    public string Index()
    {
        return "API Methods";
    }

    // GET: /Api/DetectionActivity
    public JsonResult DetectionActivity()
    {
        var detections = from d in db.Detections
                         orderby DbFunctions.TruncateTime(d.CreationTime)
                         group d by DbFunctions.TruncateTime(d.CreationTime) into g
                         select new { date = g.Key, count = g.Count() };
        ViewBag.DetectionCounts = detections.ToList();
        return Json(detections, JsonRequestBehavior.AllowGet);
    }

我的RouteConfig.cs有以下注册路线。

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

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

这看起来像我正在阅读的教程,但它不起作用,我可能遗漏了一些东西。

如果我转到localhost:21574 / api,我会看到Index()动作的输出," API Methods"。

如果我转到localhost:21574 / api / DetectionActivity,它会在响应中抛出404以及以下数据:

{
    "Message":"No HTTP resource was found that matches the request URI 'http://localhost:21574/Api/DetectionActivity'.",
    "MessageDetail":"No type was found that matches the controller named 'DetectionActivity'."
}

我认为我需要做的事情不是我。

关于下一步该怎么做的任何建议?

更新1

我用RouteConfig.cs

尝试了这个
        routes.MapRoute(name: "ApiController",
            url: "{controller}/{action}"
        );

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

这些是我的结果:

如果我转到localhost:21574 / api,我会看到Index()操作的输出," API Methods"。和以前一样。

如果我转到localhost:21574 / api / DetectionActivity,它会在响应中抛出404以及以下数据:

{
    "Message":"No HTTP resource was found that matches the request URI 'http://localhost:21574/Api/DetectionActivity'.",
    "MessageDetail":"No type was found that matches the controller named 'DetectionActivity'."
}

与以前相同。

如果我转到localhost:21574 / Api / Api / DetectionActivity,它会在响应中抛出404这些数据:

{
    "Message":"No HTTP resource was found that matches the request URI 'http://localhost:21574/Api/Api/DetectionActivity'.",
    "MessageDetail":"No type was found that matches the controller named 'Api'."
}

现在它说它找不到名为" Api"的控制器。

1 个答案:

答案 0 :(得分:0)

路线配置中的

该网址应为:localhost:21574/Api/Dashboard/DetectionActivity

或者如果你真的需要localhost:21574/Api/DetectionActivity(不推荐)

Register课程中的WebApiConfig方法更改为

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