我正在使用 VS 2017 社区。多年来我一直在构建 web api。但一定有什么地方发生了变化,因为我无法使用最简单的示例。
我在 Controller 文件夹中有一个简单的 Controller
public class TestApi : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
我在应用程序启动时有必要的代码:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
但是当我尝试使用 get 来测试 web api 时:
http://localhost:54014/api/testapi
我总是收到一条 xml 消息
Error
Message
No HTTP resource was found that matches the request URI
'http://localhost:54014/api/testapi'.
/Message
MessageDetail
No type was found that matches the controller named 'testapi'.
/MessageDetail
/Error
这是 WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
我为此苦思冥想了几个小时。正如我所说,我已经构建了许多 MS web api 实现,而这个实现让我感到困惑。
请您参考如下方法:
您应该在您的类名中添加 Controller 后缀。
public class TestApiController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
当应用程序启动时,asp.net mvc 框架会查找具有此后缀的类(继承自 ApiController 或 Controller)并在构建路由时注册它们 table 。当请求到达您的应用程序时,框架再次查看路由表并将请求定向到相应的 Controller 和操作方法。
进行此更改,重新构建您的项目并重试。
