【问题标题】:How to consume DELETE request from windows client application如何使用来自 Windows 客户端应用程序的 DELETE 请求
【发布时间】:2018-08-22 23:12:31
【问题描述】:

在我的 web API 删除请求中,它包含多个参数。我需要使用 C# windows 窗体应用程序和我的代码来使用这个 DELETE 请求。

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

这就是我使用 Postman 使用它的方式,它工作正常http://localhost:2733/api/person/1/5/"paul" 如何使用我的 Windows 客户端使用它。我试试这两种方法,

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

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

但这些都不起作用。如何将参数传递给 DELETE 请求。

更新:

这是我的控制器类,

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

这是 Person 类

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

【问题讨论】:

  • 我认为你用错了“消费”这个词。您将发出来自客户端的删除请求。
  • “不工作”并不能很好地描述问题所在。
  • 使用 UI 阻塞 async API 会导致死锁 (.Result)。一直异步或根本不异步。 blog.stephencleary.com/2012/07/dont-block-on-async-code.html
  • 在 1 和 5 之间不需要/ 吗?
  • 试试var response = client.DeleteAsync($"api/person/{p.ID}/{p.SID}/{p.Name}").Result;

标签: c# rest asp.net-web-api2 url-parameters http-delete


【解决方案1】:

试试下面的。它应该复制您尝试通过 PostMan 使用 API 的方式。

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

【讨论】:

  • 先生此代码打印成功并且应用程序中没有任何错误显示,但记录没有被删除
  • @Rooter 我的意思是,据我们所知,您甚至还没有发布您的控制器代码,它是一个空函数,只要路线正确,它就会始终返回 Success(它是因为你得到了回复)。尝试编辑您的问题或创建一个新问题,显示您的控制器代码可能(并且很可能会)是一个与您的初始问题无关的完全独立的问题。
  • @Rooter 没问题,那么您在 Api 方面是否遇到任何异常?你能告诉我们sql变量的值是什么吗?
  • API 先生没有任何错误。如何查看sql变量sir的值?
  • 先生,当我使用 Windows 窗体 p.name = "paul" 使用 API 时,我在这一行中添加了一个换行符 string sql = $"DELETE from person WHERE ID = {p.ID} AND SID = {p.SID} AND Name= {p.Name}";,但是当我使用 Postman 使用它时,p.name = "\"paul\" "
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 2022-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-02
  • 2022-09-24
相关资源
最近更新 更多