【问题标题】:Web API HttpDelete - how to call delete API method and send a model in [FromBody]Web API HttpDelete - 如何调用删除 API 方法并在 [FromBody] 中发送模型
【发布时间】:2020-08-27 05:20:08
【问题描述】:

我正在尝试通过在 url 中发送参数来调用 HttpDelete RESTful Web API 方法。调用成功。

例子

string url = path + "deletemethodName?Id=" + Convert.ToInt32(idpamameter) + "&name=" + nameParameter;
                using (HttpClient client = new HttpClient())
                {
                    using (HttpResponseMessage response = client.DeleteAsync(url).Result)
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            return Json(response.Content.ReadAsStringAsync().Result);
                        }
                       }
                }

有没有办法——在调用 HttpDelete 方法时,就像我们使用在 body 中发送模型数据调用 POST 方法和在 API 方法中使用 [FromBody] 来访问模型数据而不是在网址?

由于我的 HttpDelete 方法中有超过 5 个参数要附加到 URL 中 - 我希望发送模型数据。

提前致谢。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api2 webapi http-delete


    【解决方案1】:

    更高级别的DeleteAsync 不支持body,但我们可以在“很长的路”中做到这一点:

    var request = new HttpRequestMessage {
        Method = HttpMethod.Delete,
        RequestUri = new Uri("http://mydomain/api/something"),
        Content = new StringContent(JsonConvert.SerializeObject(myObj), Encoding.UTF8, "application/json")
    };
    var response = await client.SendAsync(request);
    

    【讨论】:

    • 谢谢你试试这个。这不会影响性能知道吗?
    【解决方案2】:

    您可以通过 post 方法删除记录。 如果您以表格格式显示您的记录,那么我们使用 Foreach 循环并在该循环内使用 Html 表单,如下所示:

    using(Html.BeginForm("ACTIONNAME","CONTROLLERNAME", new { id=item.id, ..... }))

    然后添加

     <input typer="submit" value="Delete"/>
    

    用于将数据发布到您的操作控制器。

    【讨论】:

      猜你喜欢
      • 2016-12-25
      • 2016-08-24
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-26
      相关资源
      最近更新 更多