public async void GetWeatherInfo(CityName city)
{
var httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(city);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var uri = new Uri(string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&appid=29d06aa8c8b3a8341ab876b124d7c&units=metric",json));
var result = await httpClient.GetAsync(uri);
if (result.IsSuccessStatusCode)
{
try
{
var weatherInfo = JsonConvert.DeserializeObject<WeatherInfo>(**result**);
}}}
我正在开发一个天气应用程序项目,我正在尝试从用户那里获取一个字符串城市名称。我将城市名称绑定(bind)到 url 并编写了 GetRequest,但在代码末尾出现“ 结果”的错误。它应该反序列化响应,以便我可以更改响应并使用它。错误信息是:无法从“System.Net.Http.HttpResponseMessage”转换为“字符串”
最佳答案
解释HttpClient.getAsync()
方法,返回 Task<HttpResponseMessage>
其中还包括状态代码和有关响应本身的更多信息。
Returns Task{HttpResponseMessage}
The task object representing the asynchronous operation.`
Check documentation here
您需要从结果中提取内容。
解决方案
试试这个
public async void GetWeatherInfo(CityName city)
{
var httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(city);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var uri = new Uri(string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&appid=29d06aa8c8b3a8341ab876b124d7c&units=metric",json));
var result = await httpClient.GetAsync(uri);
if (result.IsSuccessStatusCode)
{
try
{
string content = await result.Content.ReadAsStringAsync();
var weatherInfo = JsonConvert.DeserializeObject<WeatherInfo>(content);
}}}
关于c# - 如何修复错误代码 CS1503?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59157650/