WebAPI 控制器不工作而另一个控制器不工作

WebAPI controller not working while another one does

我有一个 API 在本地运行良好,但当我将其移至实时环境时却无法运行。

受影响控制器上的主要 POST 操作 returns:

NotFound

通过测试 GET 操作,我返回:

"Message": "No HTTP resource was found that matches the request URI

奇怪的是,当我上传一个测试操作与主控制器中使用的测试操作相同的 testController 时,我从 API.

得到了正确的响应

这是运行良好的测试:

public class TestController : ApiController
{

    [AllowAnonymous]
    [HttpGet]
    public HttpResponseMessage helloWorld()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "HelloWorld!");
    }
}

不工作的控制器:

public class DeviceController : ApiController
{

    [AllowAnonymous]
    [HttpGet]
    public HttpResponseMessage helloWorld() // This returns: "No HTTP resource was found that matches the request URI 'http://api.mySite.com/api/Device/helloWorld'."
    {
        return Request.CreateResponse(HttpStatusCode.OK, "HelloWorld!");
    }

    [AllowAnonymous]
    [HttpPost]
    public HttpResponseMessage Login([FromBody] LoginObject loginObject) // This returns: "NotFound"
    {
        ...
    }

}

这是网络配置:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(

            name: "API Default",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }

        );
    }
}

尝试像 acrion 那样添加明确的路由声明

[Route("api/Device/helloWorld")]
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage helloWorld() 

[RoutePrefix("api/Device")]
public class DeviceController : ApiController

然后

[Route("helloWorld")]
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage helloWorld() 

以后像我这样的笨蛋:确保控制器上的方法是public。