c# - 如何修复错误代码 CS1503?

标签 c# xamarin xamarin.forms error-handling httpresponse

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/

相关文章:

c# - 这是 async void 的正确用法吗? Xamarin

c# - Xamarin C# 读取消息 |覆盖错误

ios - Xamarin Forms iOS 状态栏文本颜色

c# - IQueryable 和 List<int> 之间的 Linq 连接执行时间太长

c# - 如何从另一个页面的代码后面访问变量?

c# - 有没有办法将设计器文件与其 cs 文件重新绑定(bind)/关联?

xamarin.ios - Xamarin.UITest System.Xml.XmlException

c# - 编码 UTF8 C# 过程

c# - C# mono 出现奇怪的编译器错误

c# - Xamarin BindableProperty 仅在我不使用 BindingContext 时才使用绑定(bind)