【问题标题】:C# HttpClient: How to send query strings in POST RequestsC# HttpClient:如何在 POST 请求中发送查询字符串
【发布时间】:2021-09-18 00:36:40
【问题描述】:

这是 POST 请求,它有效。

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

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

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


方法 1(失败,响应 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 接受请求正文而不是查询字符串时才有效。


方法 2(失败,响应 404) https://stackoverflow.com/a/37443799/7768490

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

【问题讨论】:

  • 可能你的端点有问题。
  • 不,它已经在 Swagger、Postman、Axios 上进行了测试。
  • 从 404 开始,您必须发布您的控制器和操作标头

标签: c# post dotnet-httpclient


【解决方案1】:

显然,所有尝试过的方法都没有将参数放在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);
  }

【讨论】:

  • 你可能不想要refId =中的空间
  • @RowanSmith 我重用了 OP 代码,欢迎编辑。
  • 感谢您的努力,但不,这不起作用。结果相同。我无法在此处发布我的生产 API URL,但我认为这不是格式问题。
  • @JayPow,建议如果你的body为null,将endpoint改为接受GET请求
  • @JayPow 根据您的应用程序的上下文,不等待您的异步调用可能会导致big problems。如果您要进行异步调用,请使您的方法异步。如果您不需要异步,请进行同步调用 (Send)。
猜你喜欢
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-19
  • 1970-01-01
  • 1970-01-01
  • 2022-06-19
相关资源
最近更新 更多