【问题标题】:Api working fine in Postman but not in code Xamarin FormsApi 在 Postman 中运行良好,但在 Xamarin Forms 代码中运行良好
【发布时间】:2019-11-25 22:42:32
【问题描述】:

我在 web api 中有这个请求

            Connection();
            SqlCommand cmd = new SqlCommand("[dbo].[SetIDByPhoneNumber]", conn);
            cmd.Parameters.AddWithValue("@PhoneNumber", student.PhoneNumber);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            conn.Open();
            int i=  cmd.ExecuteNonQuery();
            conn.Close();
            if (i >= 1)
            {
                response.Massage = "Found One";
                response.Status = 1;
            }
            else
            {
                response.Massage = "Nothing -_-";
                response.Status = 0;
            }

Xamarin 表单中的这个 Post 方法

string url = "MY URL (Which is a real website IP ADDRESS)";
        HttpClient client = new HttpClient();
        string jsonData = JsonConvert.SerializeObject("Student.PhoneNumber");
        StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
        HttpResponseMessage response = await client.PostAsync(url, content);
        string result = await response.Content.ReadAsStringAsync();
        Response responseData = JsonConvert.DeserializeObject<Response>(result);

Here you can see api is working well in Postman

在 Android 上运行它后,我得到“对象引用未设置为对象的实例”和响应 0

我不知道是什么问题。我的 SQL 存储过程运行良好 api 运行良好。

【问题讨论】:

    标签: c# xamarin asp.net-web-api xamarin.forms


    【解决方案1】:

    您的jsonData 不是 JSON,请尝试:

    string jsonData = JsonConvert.SerializeObject(new { PhoneNumber = "45656" });
    

    【讨论】:

    • 天哪,你救了我的命!我在这个问题上堆了 2 天。谢谢
    • 乐于帮助@MahirMuzahid ?
    【解决方案2】:

    我认为您的返回类型已关闭。你这样做应该设置适当的标题,它应该被识别为有效的 json。

    public JsonResult YourAction()
    {
        // Your Code
        return Json(new {student.PhoneNumber});
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 2017-06-16
      • 1970-01-01
      • 2020-06-04
      相关资源
      最近更新 更多