Web Api 2 - 未找到与请求URI匹配的HTTP资源

时间:2017-03-28 10:18:14

标签: routes asp.net-web-api2 asp.net-apicontroller

我的解决方案中有一个MVC项目,其中也包含ApiControllers。 我已在IIS中设置项目并将其添加到hosts文件中。

路线如下:

GlobalConfiguration.Configuration.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional });

我在Project.Web / Controllers文件夹中添加了一个名为TestController的控制器,它有一个方法,它只返回一个这样的字符串:

public class TestController : ApiController
{
    public string Get()
    {
        return "Test";
    }
}

如果我尝试通过mysite.local / api / test / get访问我的网站,我会收到以下错误:

{
  "Message": "No HTTP resource was found that matches the request URI 'http://mysite.local/api/test/get'.",
  "MessageDetail": "No type was found that matches the controller named 'test'."
}

但是如果我从Visual Studio 17启动网站,我就可以访问localhost:portnr / api / test / get而没有任何错误。

我尝试添加[Route()][RoutePrefix()]但没有成功 我也尝试将Apicontroller移动到Project.Web / Controllers / Api而没有任何成功

有谁知道为什么我能通过localhost到达它,但不能通过域名来访问它?

此致 大卫

1 个答案:

答案 0 :(得分:0)

您不需要传递名称为“动作方法”的名称为“Get。”的名称。

您需要将路由配置中的更改恢复为默认配置,如果您希望使用自定义路由,请使用路由注释。

    config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

默认情况下,API会理解,如果您使用此网址" http://sampleweb.com/api/test"这会调用你的get方法。