为什么PostAsJsonAsync的参数不作为JSON内容包含在帖子中?

时间:2016-04-26 16:34:30

标签: json xamarin xamarin.ios

非常令人失望的是,一周后我无法解决将JSON内容发布到Web服务器API的简单问题。我想我会放弃使用Xamarin的这种尝试。

我正在尝试使用Xamarin应用中的PostAsJsonAsync发布下面的JSON参数。该程序确实发布了网站,但参数未编码为JSON内容。有谁知道为什么?

public async void Login()
{
    var formcontent = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string,string>("email","marcio@netopen.com.br"),
        new KeyValuePair<string, string>("password","Xy345")
    });
    var FlyVIPAPI = new HttpClient();
    var request = await FlyVIPAPI.PostAsJsonAsync("http://www.ik.com.br/app/api/LoginUser.php", formcontent);
    var response = await request.Content.ReadAsStringAsync();
    //var res = JsonConvert.DeserializeObject(response);
    var RepostaJson = Newtonsoft.Json.Linq.JObject.Parse(response);
    System.Diagnostics.Debug.WriteLine(RepostaJson["success"]);
    System.Diagnostics.Debug.WriteLine(RepostaJson["error"]);
    return;
}

1 个答案:

答案 0 :(得分:0)

public class LoginRequest
{
    public string email { get; set; }
    public string password { get; set; }
}

public async void Login()
{
    using (var FlyVIPAPI = new HttpClient())
    {
        // Create Request object
        var requestObj = new LoginRequest { email = "marcio@netopen.com.br", password = "Xy345" };

        // Serialize to JSON string
        var formcontent = JsonConvert.SerializeObject(requestObj);

        // Create HTTP content
        var content = new StringContent(formcontent, Encoding.UTF8, "application/json");

        // POST Request
        var request = await FlyVIPAPI.PostAsync("http://www.ik.com.br/app/api/LoginUser.php", content);

        // Read Response
        var response = await request.Content.ReadAsStringAsync();

        ....
    }
}

此外,我建议将HttpClient包装在using语句中,以便在代码块完成后将其处理掉。释放资源。