无法将字符串转换为 system.Net.HttpContent [重复]
Posted
技术标签:
【中文标题】无法将字符串转换为 system.Net.HttpContent [重复]【英文标题】:Can't convert string to system.Net.HttpContent [duplicate] 【发布时间】:2019-06-29 00:01:55 【问题描述】:我在这里尝试从服务中获取数据:
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 方法都不接受字符串。尝试传递字符串会引发编译错误。 【参考方案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);
【讨论】:
以上是关于无法将字符串转换为 system.Net.HttpContent [重复]的主要内容,如果未能解决你的问题,请参考以下文章