C# HttpClient:如何在 POST 请求中发送查询字符串

C# HttpClient: How to send query strings in POST Requests

这是 POST 请求,有效。

curl -X POST --header 'Accept: application/json' 

'http://mywebsite.com/api/CompleteService?refId=12345&productPrice=600'

如何使用 C# => HttpClient => client.PostAsync() 方法发送这个请求? 两种方法都试过了,都失败了。


方法一(失败,响应404)

string url = "http://mywebsite.com/api/CompleteService";
string refId = "12345";
string price= "600";
string param = $"refId ={refId}&productPrice={price}";
HttpContent content = new StringContent(param, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(url, content).Result;

这仅在 API 接受请求正文而不是查询字符串时有效。


方法二(失败,响应404)

var parameters = new Dictionary<string, string> { { "refId ", refId }, { "productPrice", price} };
var encodedContent = new FormUrlEncodedContent(parameters);
HttpResponseMessage response = client.PostAsync(url, encodedContent)

显然,None 的尝试方法将参数放在 URL! 中。您在下面发帖 URL

"http://mywebsite.com/api/CompleteService"

然而,一些有用的东西

string url = "http://mywebsite.com/api/CompleteService?";
string refId = "12345";
string price= "600";
string param = $"refId={refId}&productPrice={price}";
HttpContent content = new StringContent(param, Encoding.UTF8, "application/json");

将参数附加到 URL 并获取响应的正文,使用:

  try   
  {
     HttpResponseMessage response = await client.PostAsync(url + param, content);
     response.EnsureSuccessStatusCode();
     string responseBody = await response.Content.ReadAsStringAsync();
     Console.WriteLine(responseBody);
  }
  catch(HttpRequestException e)
  {
     Console.WriteLine("Message :{0} ",e.Message);
  }