【发布时间】:2020-08-26 07:40:08
【问题描述】:
我有一个在本地运行良好的 API,但当我将它移到实时环境时却不行。
受影响控制器上的主要 POST 操作返回:
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 }
);
}
}
【问题讨论】:
-
所以
http://api.mySite.com/api/Test/helloWorld有效,对吧? -
是的,我得到了“HelloWorld!”背部。这看起来很奇怪……一定是路由问题?
-
嗯...让我们检查一下。尝试添加路由属性
[Route("api/Device/helloWorld")] -
啊,好的,它现在正在工作。我想知道为什么另一个控制器的路由没有明确声明就可以了...随意添加这个作为答案,我会接受它。谢谢!
标签: asp.net-web-api asp.net-web-api-routing