Search code examples
c#restasp.net-web-api2url-parametershttp-delete

How to consume DELETE request from windows client application


In my web API delete request, which containing multiple parameters.I need to consume this DELETE request using C# windows form application and my code as bellow.

    private void btnDelete_Click(object sender, EventArgs e)
    {
        using (var client = new HttpClient())
        {
            person p = new person { ID = 1, SID = 5, Name = "paul"};

            client.BaseAddress = new Uri("http://localhost:2733/");
            var response = client.DeleteAsync("api/person/").Result;
            if (response.IsSuccessStatusCode)
            {
                Console.Write("Success");
            }
            else
                Console.Write("Error");
        }
    }

This is how I consume this using Postman, and its works finehttp://localhost:2733/api/person/1/5/"paul" How to consume this using my windows client. I try these two way,

var response = client.DeleteAsync("api/person/",p).Result;

and

var response = client.DeleteAsync("api/person/"+1+5+"paul").Result;

But those are not working. How can I pass parameters to DELETE request.

Updated:

This is my controller class,

[Route("api/person/{id:int}/{pid:int}/{pname}")]
[HttpDelete]
public void Delete(int id, int pid, string pname)
{
    var pModel = new PModel
    {
        ID = id,
        SID = pid,
        Name= pname
    };
    Person p = new Person();
    p.deletePerson(pModel);
}

This is Person class

public void deletePerson(PModel p)
{
    try
    {
        string sql = $"DELETE from person WHERE ID = {p.ID} AND SID = {p.SID} AND Name= {p.Name}"; ;
        MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sqlString, conn);
        cmd.ExecuteNonQuery();
        long x = cmd.LastInsertedId;
    }
    catch (MySqlException x)
    {
        int errr = x.Number;

        Console.WriteLine(errr);
    }
}

Solution

  • Try the below. It should replicate the way you have tried consuming your API through PostMan.

    var response = client.DeleteAsync($"api/person/{p.ID}/{p.SID}/\"{p.Name}\"").Result;