C#Web API路由POST始终返回404

时间:2019-02-07 16:35:57

标签: c# asp.net web-services asp.net-web-api2

我对使用ASP.NET Web API 2路由POST请求有疑问。

我似乎无法调用POST函数,它总是返回找不到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
    });

1 个答案:

答案 0 :(得分:2)

首先,在以下代码中

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