【问题标题】:How to post int array using $http to a ASP.Net Web Api Controller method如何使用 $http 将 int 数组发布到 ASP.Net Web Api 控制器方法
【发布时间】:2013-11-14 19:25:10
【问题描述】:

我正在尝试使用 $http 向 ASP.Net Web API 控制器方法发布要从服务中删除的整数数组。我都试过了

[HttpDelete]
public HttpResponseMessage DeleteMany(int[] ids) { }

[HttpDelete]
public HttpResponseMessage DeleteMany(DeleteManyDto dto) { }

public class DeleteManyDto
{
    public int[] Ids {get;set;}
}

我一直将参数设为空。我在 Angular 服务中尝试了几种变体。这是一个例子

this.deleteMany = function(ids) {
// ids is an int array. e.g. [1,4,6]
    return $http.delete('api/Foo/DeleteMany', { toDelete: ids }).then(function(result) {
        return result.status;
    });
};

有人知道我可能会错过什么吗?

更新:拼写错误。包含来自 HTTP 请求的调试。

Request URL:http://localhost:54827/api/Foo/DeleteMany
Request Method:DELETE
Status Code:500 Internal Server Error
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Cookie:__RequestVerificationToken=blabla
Host:localhost:54827
Origin:http://localhost:54827
Pragma:no-cache
Referer:http://localhost:54827/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
Response Headersview source

上面的代码没有产生任何请求负载。当我进行更新时,我会看到请求有效负载。示例

Request Payloadview parsed
{"id":4,"name":"zzzz", "bar": 2}

值得我使用 Angular 1.2.rc3

【问题讨论】:

  • 请求 json 的外观如何。在您的浏览器调试器控制台中查看,并在此处发布一些详细信息。
  • 根据 HTTP 语义,DELETE 应该删除正在考虑的资源。 url 指向资源位置,因此不需要任何有效负载。您正在尝试做的不是严格遵守 DELETE 的用法。
  • @Chandermani 其他人建议我使用 post。我想这不会很平静。我们应该一次删除一个吗?即使可能有 100 个?

标签: asp.net-mvc-4 angularjs asp.net-web-api


【解决方案1】:

尝试将您的控制器方法签名更改为:

[HttpDelete]
public HttpResponseMessage DeleteMany(int[] toDelete) { }

或者如果您使用 ViewModel 而不是将删除调用更改为:

return $http.delete('api/Foo/DeleteMany', { Ids: ids }).then(function(result) {
        return result.status;
    });

编辑:

但我认为真正的问题在于 $http.delete 调用。您不能在 HTTP 中使用 DELETE 动词发送正文,并且因为 MVC 绑定来自消息正文或 url 的数据,所以您的数组未绑定。 尝试使用 POST 请求实现 DeleteMany

http://docs.angularjs.org/api/ng.$http#methods_delete

您在文档中看到删除方法的定义中没有数据参数。

或者您可以尝试这种方法,将数据添加到邮件标题:

What is a clean way to send a body with DELETE request?

【讨论】:

  • 都试过了。都没有奏效。似乎角度没有添加请求有效负载。
  • 我最终使用了带有 int 数组的 HTTP 帖子。
【解决方案2】:

您的 API 中有拼写错误:

public HttpResponseMessage DeleteManay(int[] ids) { }

应该是:

public HttpResponseMessage DeleteMany(int[] ids) { }

更新:

似乎是问题中的拼写错误。

【讨论】:

  • 对不起。在我的代码中是正确的。我只是在这里直接输入文本编辑器。它正在调用该方法。 ids 参数为空。所以我认为路由匹配是有效的。
猜你喜欢
  • 1970-01-01
  • 2013-08-07
  • 2021-01-19
  • 1970-01-01
  • 2020-10-05
  • 1970-01-01
  • 2014-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多