【问题标题】:C# Web API route POST always returns 404C# Web API 路由 POST 总是返回 404
【发布时间】:2019-07-01 20:21:08
【问题描述】:

我有一个关于使用 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
    });

【问题讨论】:

  • 我不确定,但我认为有时默认情况下,路由会省略 post 部分,您可以尝试仅使用 CombinedPOResponse 调用它吗?
  • 现在您正在为控制器 and 操作使用相同的名称。您可能应该将 Post 操作命名为 Post。

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


【解决方案1】:

首先,在下面的代码中

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 2020-11-11
    相关资源
    最近更新 更多