user2294434
user2294434

Reputation: 163

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

I am trying to call a HttpDelete restful web API method, by sending the parameters in the url. Call is successful.

Example

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

Is there a way- while calling the HttpDelete method, just like how we use to call POST method with model data sent in the body and by using [FromBody] in API method, to access model data instead of sending it in the URL ?

Since I have more than 5 parameters in my HttpDelete method to be appended in the URL - I am looking to send a model data.

Thanks in advance.

Upvotes: 2

Views: 5202

Answers (2)

Mayur Asodariya
Mayur Asodariya

Reputation: 103

You cal delete records by post method. If you are displaying your records in table format then us Foreach loop and inside that loop use Html Form Like below :

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

Then add

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

For post data to your action controller.

Upvotes: 0

Roman Ryzhiy
Roman Ryzhiy

Reputation: 1656

The higher-level DeleteAsync doesn't support a body, but we can do it in the "long way":

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

Upvotes: 5

Related Questions