C#Web API路由POST始终返回404
我有一个关于使用ASP.NET Web API 2路由POST请求的问题 我似乎无法调用POST函数,它总是返回not found 404C#Web API路由POST始终返回404,c#,asp.net,web-services,asp.net-web-api2,C#,Asp.net,Web Services,Asp.net Web Api2,我有一个关于使用ASP.NET Web API 2路由POST请求的问题 我似乎无法调用POST函数,它总是返回not found 404 { "Message": "No HTTP resource was found that matches the request URI 'https://....../api/CombinedPOResponse/PostCombinedPOResponse'.", "MessageDetail": "No action was found
{
"Message": "No HTTP resource was found that matches the request URI 'https://....../api/CombinedPOResponse/PostCombinedPOResponse'.",
"MessageDetail": "No action was found on the controller 'CombinedPOResponse' that matches the request."
}
有人能指出我的配置被破坏的地方吗?
以下是控制器的相关部分
namespace FormSupportService.Controllers
{
public class CombinedPOResponseController : ApiController
{
[HttpPost]
public IHttpActionResult PostCombinedPOResponse(string inputXml)
{
AddPurchaseOrderResponse response = new AddPurchaseOrderResponse();
//...
return Ok(response);
}
//...
}
}
以及WebApiConfig.cs摘录
// UnitCodeLookup
config.Routes.MapHttpRoute(
name: "CombinedPOResponseApi",
routeTemplate: "api/{controller}/{action}",
defaults: new { inputXml = RouteParameter.Optional }
);
我可以毫无问题地联系到所有其他控制器,但这一个很棘手
多谢各位
编辑:
我正在使用javascript调用该服务:
$.ajax("/api/CombinedPOResponse/PostCombinedPOResponse",
{
accepts: "text/html",
data: {inputXml: inputXml},
dataType: 'json',
method: 'POST',
error: error,
success: success
});
首先,在下面的代码中
config.Routes.MapHttpRoute(
name: "CombinedPOResponseApi",
routeTemplate: "api/{controller}/{action}",
defaults: new { inputXml = RouteParameter.Optional } //this line is not necessary
);
设置inputXml
默认值不是必需的,您可以忽略此项
要使请求生效,必须将[FromBody]
添加到操作参数
[HttpPost]
public IHttpActionResult PostCombinedPOResponse([FromBody] string inputXml)
{
AddPurchaseOrderResponse response = new AddPurchaseOrderResponse();
//...
return Ok(response);
}
如果您尝试使用此代码,则除了inputXml
将始终为null
之外,其他一切都将正常工作。要解决这个问题,您需要更新javascript
$.ajax("/api/CombinedPOResponse/PostCombinedPOResponse",
{
accepts: "text/html",
data: {"": inputXml}, //empty name
dataType: 'json',
method: 'POST',
error: error,
success: success
});
我不确定,但我认为有时候默认情况下,路由会忽略post部分,您可以尝试使用CombinedPOResponse来调用它吗?现在,控制器和操作使用相同的名称。您可能应该将
Post
操作命名为Post
。