我有一个在本地运行良好的 API,当我将其移动到实时环境时,它不起作用。
受影响控制器上的主开机自检操作返回:
NotFound
通过测试 GET 操作,我得到:
"Message": "No HTTP resource was found that matches the request URI
奇怪的是,当我上传与主控制器中使用的测试操作相同的测试控制器时,我从 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()
对于将来像我这样的可怜的树液:确保控制器上的方法都是公开的。
我创建了一个新项目(自动创建了一个WeatherForecastController
)之后,我花了一些时间在.NET 7.0中寻找这个问题的答案。
事实证明,该项目还自动创建了一个名为proxy.conf.js的文件。在文件中,context:
设置设置为 "/weatherforecast"
。我将其更改为"/api"
,然后在两个控制器文件中将[Route("[controller]")]
更改为[Route("api/[controller]")]
。之后控制器工作正常。