C# Web API 路由 POST 总是 returns 404

C# Web API route POST always returns 404

我有一个关于使用 ASP.NET Web API 路由 POST 请求的问题 2.

我似乎无法调用 POST 函数,它总是 returns 未找到 404。

{
   "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
});