注册Web API路由及其顺序 - 为什么重要

时间:2013-09-01 21:05:34

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

我正在使用ASP MVC和WebAPI,在Global.asax中我按以下顺序调用了几段代码:

RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
WebApiConfig.Register(System.Web.Http.GlobalConfiguration.Configuration);

这些方法的作用是不言自明的。但是当我按此顺序进行注册时,我无法访问Web API。但是,当我把它改为:

WebApiConfig.Register(System.Web.Http.GlobalConfiguration.Configuration);
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);

然后Web API开始工作。所以我认为注册顺序很重要。但为什么呢?

2 个答案:

答案 0 :(得分:3)

之前致电RegisterRoutes(RouteTable.Routes);

WebApiConfig.Register(System.Web.Http.GlobalConfiguration.Configuration);

MVC的默认路由优先,并且没有任何东西进入WebApi路由。

答案 1 :(得分:0)

我对我的Global.asax进行了一些重构,将MVC配置和WebApi配置组合在一起,恰好选择了第二个WebAPI配置。

突然间,我的所有API路线都出现了这种错误:

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly. 

Requested URL: /api/values

此问题是由原始海报概述的情景引起的。

请务必先注册您的API路线。