Web API HttpDelete - 如何调用 delete API 方法并在 [FromBody] 中发送模型

Web API HttpDelete - how to call delete API method and send a model in [FromBody]

我试图通过在 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 方法时,就像我们使用在正文中发送的模型数据调用 POST 方法以及在 API 方法中使用 [FromBody] 一样,访问模型数据而不是在 URL ?

中发送它

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

提前致谢。

higher-level 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);

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

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

然后添加

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

将 post 数据发送到您的操作控制器。