我正在尝试让 API 控制器在 ASP.NET MVC 4 Web 应用程序中工作。但是,每个请求都会导致404,我很难过。:/
我有来自项目模板的标准 API 控制器路由,定义如下:
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 中调用注册:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// Register API routes
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
我有一个这样的基本 API 控制器:
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方法,但我得到的是404状态代码和以下响应:
<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>
任何帮助将不胜感激,我在这里有点失去理智。:) 谢谢!