【问题标题】:POST with single parameter returns 404 error带有单个参数的 POST 返回 404 错误
【发布时间】:2014-12-03 07:14:22
【问题描述】:

我需要将单个参数传递给 Web API POST 方法。

以下是我的 AJAX 调用:

$http({ method: 'POST', url: "customers/ProcessCustomer/" + customerId })
    .success(function (data) {

    });

其中customerIdGuid

还有我的控制器:

[HttpPost]
[Route("customers/ProcessCustomer")]
public void ProcessCustomer(Guid id)
{
    //do some stuff
}

但是当我这样做时,我只会得到一个 404 not found 错误。我做错了什么?

【问题讨论】:

  • 您在查询字符串中添加参数。这不是 POST 的工作原理
  • @Jonesy customerId 不是查询字符串的一部分,而是路径的一部分。
  • @Stijn 你是对的。 Web API 能够将其转换为 POST 参数。很高兴知道,谢谢。

标签: c# ajax post asp.net-web-api


【解决方案1】:

您正在使用属性路由,但尚未在路由中指定 id 参数。改用这个:

[Route("customers/ProcessCustomer/{id}")]

更多示例请参见Attribute Routing in Web API 2

【讨论】:

    【解决方案2】:

    当您POST 到操作方法时,数据不会嵌入到 URL 中。相反,请在您的 ajax 调用中使用设置对象的 data 字段:

    // I didn't recognize what library you're using for the AJAX call, so this is jQuery
    $.ajax('customer/ProcessCustomer', {
        data: { id: customerId },
        success: function() { /* woohoo! */ }
    });
    

    【讨论】:

      猜你喜欢
      • 2015-08-06
      • 2016-09-12
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      • 1970-01-01
      • 2016-05-26
      • 2015-12-28
      • 2020-01-08
      相关资源
      最近更新 更多