【问题标题】:FormUrlEncodedContent parameters on httpclient posthttpclient post 上的 FormUrlEncodedContent 参数
【发布时间】:2019-09-13 18:23:55
【问题描述】:

我必须发布到下面列出的 html 表单中。

<input type="text" name="user[username]" value="">
<input type="password" name="user[password]" >

休息锐利它可以正常工作 - 代码如下:

var clientRest = new RestClient(url);
var restRequest = new RestRequest();

restRequest.Method = Method.POST;
restRequest.AddParameter("user[username]", username);
restRequest.AddParameter("user[password]", password);
restRequest.AddHeader("Content-Type", "application/x-www-form-urlencoded");

IRestResponse responseRestSharp = clientRest.Execute(restRequest);
string content = responseRestSharp.Content;

但是当我尝试使用 System.Net.Http 提供的 HttpClient 时,我没有在响应中登录到会话 - 代码如下:

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(@"application/x-www-form-urlencoded"));

var content = new FormUrlEncodedContent(new[]
  {
    new KeyValuePair<string, string>("user[username]", username),
    new KeyValuePair<string, string>("user[password]", password)

    string response = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
    ....

我问自己 FormUlrEncodedContent 是否正确地将其转换为 name="user[username]"name="user[password]" 就像 restsharp 使用它的 AddParameter 一样。

【问题讨论】:

  • 你得到什么错误?
  • 这有什么更新吗?

标签: c# post .net-core dotnet-httpclient


【解决方案1】:

看起来你缺少等待。您是否按照网上的示例进行操作?

string response = await client.PostAsync

【讨论】:

  • 即时调用结果这就是为什么我不需要等待并且它同步
  • 我看到的所有示例都将 await 与变量一起使用,然后使用该变量。值得一试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多