我在这里想念的是什么? IsSuccessStatusCode无效

时间:2020-06-03 05:44:44

标签: c# json xamarin

在我的代码中,我试图与php网络服务进行通信。在我的Csharp IsSuccessStatusCode中的Xamarin代码中,无效的“'string'不包含对“ isSuccessStatusCode'的定义...。我在网上看到的所有代码都包含此内容,但我不知道它对我不起作用。

private async void GetDataAsync()
{
    //nota: para que await funcione hay que escribir en la rutina al lado de private async
    HttpClient httpClient = new HttpClient();
    var response = await httpClient.GetStringAsync("http://192.168.1.33:82/usuarios_xamarin/Usuarios.php");


    if (response.IsSuccessStatusCode)
    {
        var content = await response.Content.ReadAsStringAsync();
        var posts = JsonConvert.DeserializeObject<List<Posts>>(content);
    }
    //pertenece al nugget newtonsoft.json
    //si no esta instalado hay que instalarlo en los nuggets

    //var posts = JsonConvert.DeserializeObject<List<Posts>>(response);


}

2 个答案:

答案 0 :(得分:4)

响应是一个字符串,并且字符串没有方法IsSuccessStatusCode。如果您使用GetAsync而不是GetStringAsync,则可以使用IsSuccessStatusCode的属性(response)。

Documentation on HttpClient.GetAsync Method

答案 1 :(得分:0)

是的,是的。 string没有名为IsSuccessStatusCode的属性。 HttpResponseMessage does

您正在呼叫端点,并将响应直接转换为string。如果要检查响应的状态码,则希望分两部分进行:

HttpResponseMessage response = await client.GetAsync("http://192.168.1.33:82/usuarios_xamarin/Usuarios.php");
if (response.EnsureSuccessStatusCode) 
{
    string responseBody = await response.Content.ReadAsStringAsync();
}
相关问题