【问题标题】:HTTP Client PostAsync return status 500HTTP 客户端 PostAsync 返回状态 500
【发布时间】:2020-10-14 09:42:05
【问题描述】:

我向 API 发送 POST 请求。这是我的代码:

                    client.DefaultRequestHeaders.Add("Accept", "application/json");
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                    var postData = JsonConvert.SerializeObject(claim);
                    var response = await client.PostAsync($"api/Claims/Save", new StringContent(postData, Encoding.UTF8, "application/json"));

我序列化对象并发送,但在 API 中我的代码是这样的:

   [System.Web.Http.HttpPost]
        public IHttpActionResult Save(string user , string description , string data)

如果是 HTTP GET,我知道您在 url 上添加了参数,但我不知道如何使用 HTTP POST。问题是我无法更改 API 请求。

Claim 对象包含字符串用户、字符串描述、字符串数据

API 不是我的,我无法修改。

【问题讨论】:

    标签: c# http-post httpclient


    【解决方案1】:

    如果有人遇到同样的情况:

    首先你需要添加 Content-Type:application/x-www-form-urlencoded

    其次,你需要根据你的价值观创建一个字典,例如:

    var dictionary = new Dictionary<string, string>();
                        dictionary.Add("values", "Doctor");
                        dictionary.Add("name", "John");
                        dictionary.Add("surname", "Doe");
                        dictionary.Add("Year", "1993");
    

    第三,你需要像这样对内容进行编码:

    var content = new FormUrlEncodedContent(dictionary);

    最后发送请求:

    var response = await client.PostAsync($"api/Claims/Save", content);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-13
      • 2017-03-09
      • 2020-08-27
      • 2012-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多