【问题标题】:Can't convert string to system.Net.HttpContent [duplicate]无法将字符串转换为 system.Net.HttpContent [重复]
【发布时间】:2023-03-28 13:25:02
【问题描述】:

我在这里尝试从服务中获取数据:

public async Task<IHttpActionResult> ValidateSesion()
{
    var values = new Dictionary<string, string>{
        { "productId", "1" },
        { "productKey", "Abc6666" },
        { "userName", "OPPO" },
    };
    var json = JsonConvert.SerializeObject(values, Formatting.Indented);
    // var content = new FormUrlEncodedContent(json);
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var response = await client.PostAsync("http://172.116.12.172:8014/iadmin/validate", json);
    var responseString = await response.Content.ReadAsStringAsync();
    return Ok(responseString);
}

如果我拨打任何 PostMan 电话,如下所示,我得到的数据如下所示:

{
    "productId": "1",
    "productKey": "Abc6666" 
}

【问题讨论】:

  • 你能提供你的错误的完整堆栈跟踪吗?这可以帮助我们确定错误发生的确切位置...
  • 所有 PostAsync 方法都不接受字符串。尝试传递字符串会引发编译错误。

标签: c# json asp.net-web-api dotnet-httpclient


【解决方案1】:

您不能发布原始字符串,您必须将其包装在 StringContent 中: new StringContent(json);

这应该可以解决问题:

public async Task<IHttpActionResult> ValidateSesion()
{
    var values = new Dictionary<string, string>{
      { "productId", "1" },
      { "productKey", "Abc6666" },
      { "userName", "OPPO" },
    };

    var json = JsonConvert.SerializeObject(values, Formatting.Indented);

    var stringContent = new StringContent(json);

    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var response = await client.PostAsync("http://172.116.12.172:8014/iadmin/validate", stringContent);

    var responseString = await response.Content.ReadAsStringAsync();

    return Ok(responseString);
}

【讨论】:

    【解决方案2】:

    更改您的退货声明,如

    return Content(responseString);
    

    【讨论】:

      猜你喜欢
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      • 2019-05-11
      • 2013-01-12
      • 1970-01-01
      • 1970-01-01
      • 2017-01-31
      • 2019-06-14
      相关资源
      最近更新 更多