将 HttpResponseMessage 转换为对象

Joy*_*nna 5 http xamarin xamarin.forms

我有这个结构,我也在使用System.Net.HttpNewtonsoft。我需要接收 webservice 响应并在我的班级中转换它,但我不知道如何使用 HttpResponseMessage 来做到这一点,而且我红色的帖子对我没有帮助。这是一个 Xamarin.forms 项目。

 public static async Task<User> PostLoginAsync(string login, string senha)
    {
        using (var client = new HttpClient())
        {
            try
            {
                login = "email@hotmail.com";
                senha = "1111111";

                var content = new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair<string, string>("id", "1200"),
                        new KeyValuePair<string, string>("email", login),
                        new KeyValuePair<string, string>("password", senha),
                        new KeyValuePair<string, string>("json", "1"),
                     });

                HttpResponseMessage response = await client.PostAsync("http://ws.site.com", content);

                return null;
            }

            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return null;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我的课:

class User
{
    public string codigo { get; set; }
    public string nome { get; set; }
    public string email { get; set; }
    public string senha { get; set; }
    public string imagem { get; set; }
    public DateTime dataDeNasc { get; set;}
    public string cidade { get; set; }
    public string estado { get; set; }
    public string telefone { get; set; }
    public string sexo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如果你能帮助我......我将不胜感激。还是谢谢你

teq*_*mer 9

您需要等待来自 HttpResponseMessage 的内容。

public static async Task<User> PostLoginAsync(string login, string senha)
{
    using (var client = new HttpClient())
    {
        try
        {
            login = "email@hotmail.com";
            senha = "1111111";

            var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("id", "1200"),
                    new KeyValuePair<string, string>("email", login),
                    new KeyValuePair<string, string>("password", senha),
                    new KeyValuePair<string, string>("json", "1"),
                 });

            HttpResponseMessage response = await client.PostAsync("http://ws.site.com", content);

            var responseContent = await response.Content.ReadAsStringAsync();
            var user = JsonConvert.DeserializeObject<User>(responseContent);

            return user;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            return null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)