使用web api的无响应Xamarin android应用程序

时间:2016-12-20 08:08:15

标签: asp.net-web-api xamarin.android

您好,我只是在学习Xamarin android开发,我只是想进行CRUD操作,但我感到困惑,我无法从webapi得到任何回复。我已经使用SOAPUI测试了我的api,并且响应是可以的。

[HttpPost]
public HttpResponseMessage CreateEmpAttandance(string value)
{
    if (value != "1234")
    {
        string json = @"{ data: 'Emp Code is not valid.'}";
        var jObject = JObject.Parse(json);

        var response = Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StringContent(jObject.ToString(), System.Text.Encoding.UTF8, "application/json");
        return response;

    }
    else
    {
        string json = @"{ data: 'data save sucessfully.'}";
        var jObject = JObject.Parse(json);

        var response = Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StringContent(jObject.ToString(), System.Text.Encoding.UTF8, "application/json");
        return response;


    }
}

这是api代码,下面是我的android应用程序代码,但我得到null响应异常。

  public async Task SaveTodoItemAsync(string EmpCode)
    {
        try
        {
            string url = "http://192.168.1.9/attandanceapi/api/attandance?value=12132";

            var uri = new Uri(string.Format(url));
            var json = JsonConvert.SerializeObject(EmpCode);
            var content = new StringContent(EmpCode, Encoding.UTF8, "application/json");
            HttpResponseMessage response = null;
            response = await client.PostAsync(url, content);

            var responses = response;
        }
        catch (Exception ex)
        {

            var w = ex.ToString();
        }
    }

1 个答案:

答案 0 :(得分:0)

我认为我们这里有问题。您正在尝试从字符串创建内容而不是从Json。

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

试试这个:

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

编辑:

我看不到你的默认标题,所以如果你没有它们 - 只需添加。

client.DefaultRequestHeaders.Add("Accept", "application/json");