【问题标题】:MVC4 WebApi Routes Returning 404MVC4 WebApi 路由返回 404
【发布时间】:2013-01-30 18:26:57
【问题描述】:

我开始了一个新的 Web Api MVC4 项目,但没有弄清楚我在路由器上做错了什么。我的简单 Get 请求路由返回 404。

这是我的路线定义:

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

        routes.MapRoute("ApiDefault", "api/{controller}/{id}",
                        new {controller = "Home", id = UrlParameter.Optional});

        routes.MapRoute("ApiDefault-CategoryLevels", "api/{controller}/{level1}/{level2}/{level3}/{level4}",
                        new
                            {
                                controller = "Home",
                                level1 = UrlParameter.Optional,
                                level2 = UrlParameter.Optional,
                                level3 = UrlParameter.Optional,
                                level4 = UrlParameter.Optional
                            });

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

我正在尝试使用 ApiDefault-CategoryLevels 路由。我安装了 Phil Haack 的 routing debugger,它显示当我浏览到这个 Url 时:

http://localhost:22283/api/Categories/a/b/c/d

我正在寻找的路线匹配:

匹配路由:api/{controller}/{level1}/{level2}/{level3}/{level4}

路线数据
核心价值
控制器类别
一级a
2级b
3级c
4级d

但是 IIS 网络服务器的返回是 404。

当我使用查询字符串以这种方式调用相同的 URL 时,它可以工作:

http://localhost:22283/api/Categories?level1=A&level2=B&level3=C&level4=D

网络请求有效,我得到了预期的结果。只有当我以第一种方式尝试请求时,它才会返回 404。

这是我的 CategoriesController 的全部内容:

public class CategoriesController : ApiController
{

    public IEnumerable<CategoryModel> Get(string level1 = null, string level2 = null, string level3 = null, string level4 = null)
    {
        return new[] {new CategoryModel()};
    }

    public CategoryModel Get(Guid id)
    {
        return new CategoryModel();
    }
}

【问题讨论】:

  • 它匹配你的控制器中不存在的动作“a”。
  • 我修复了上面的代码。对于那个很抱歉。我有一个陈旧的窗口,我从中复制和粘贴(我尝试了很多不同的东西。)上面的代码现在应该准确地反映了这个问题。 (根本没有动作,它是一个ApiController)

标签: asp.net-mvc-4 asp.net-web-api-routing


【解决方案1】:

您正在将基于 ApiController 的路由添加到 RouteTable.Routes。您应该将它们添加到 GlobalConfiguration.Configuration。也就是说,您似乎已将它们添加到 MVC 4 项目模板的 RouteConfig.RegisterRoutes(RouteCollection)。如果您使用 MVC4 Web API 项目模板,请将它们添加到 WebApiConfig.Register(HttpConfiguration) 方法中。

【讨论】:

  • 太棒了!我什至没有注意到它在那里!非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
  • 2021-02-01
  • 1970-01-01
相关资源
最近更新 更多