所有 ASP.NET Web API 控制器都返回 404 [英] All ASP.NET Web API controllers return 404
问题描述
我正在尝试让 API 控制器在 ASP.NET MVC 4 Web 应用程序中工作.但是,每个请求都会导致 404,我很难过.:/
I'm trying to get an API Controller to work inside an ASP.NET MVC 4 web app. However, every request results in a 404 and I'm stumped. :/
我有来自项目模板的标准 API 控制器路由,定义如下:
I have the standard API controller route from the project template defined like:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
在 Global.asax 中调用注册:
The registration is invoked in Global.asax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// Register API routes
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
我有一个像这样的基本 API 控制器:
I have a basic API controller like this:
namespace Website.Controllers
{
public class FavoritesController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new [] { "first", "second" };
}
// PUT api/<controller>/5
public void Put(int id)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}
现在,当我浏览到 localhost:59900/api/Favorites 时,我希望调用 Get 方法,但我得到的是 404strong> 状态代码和以下响应:
Now, when I browse to localhost:59900/api/Favorites I expect the Get method to be invoked, but instead I get a 404 status code and the following response:
<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:59900/api/Favorites'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'Favorites'.
</MessageDetail>
</Error>
任何帮助将不胜感激,我在这里有点失去理智.:) 谢谢!
Any help would be greatly appreciated, I'm losing my mind a little bit over here. :) Thanks!
推荐答案
我遇到的一件事是我的配置在 GLobal.asax 文件中以错误的顺序注册,例如:
One thing I ran into was having my configurations registered in the wrong order in my GLobal.asax file for instance:
正确的顺序:
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
顺序错误:
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
WebApiConfig.Register(GlobalConfiguration.Configuration);
只是说,这是我的问题,更改顺序很明显,但有时会被忽视,并会导致很多挫折.
Just saying, this was my problem and changing the order is obvious, but sometimes overlooked and can cause much frustration.
这篇关于所有 ASP.NET Web API 控制器都返回 404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!