微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当我将GET与参数一起使用时,为什么会出现错误

如何解决当我将GET与参数一起使用时,为什么会出现错误

我正在尝试通过WinApi从MS sql服务器检索日期。在图像1中,我正在使用参数调用GET(第二个图像)。 我在图像1中设置了一个断点,当程序到达该断点时,我将鼠标悬停在“响应”上,这表明已检索到一条记录。 当我继续并到达第二张图片中的断点并悬停在“ userAuthentication”上时,结果为“ null”。 我在邮递员中运行了网址字符串,并且可以正常工作。 还有一件奇怪的事。当不带参数的GET调用有效时,我将在“ userAuthentication”中获取所有记录。

enter image description here

enter image description here

public async Task<List<UserAuthentication>> Get(string employeeNumber)
    {
        try
        {
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("Key","1234");
            var response = await client.GetStringAsync(@"http://192.168.100.223/api/Pilot?employeeID=" + employeeNumber) ;
            return JsonConvert.DeserializeObject<List<UserAuthentication>>(response);
        }
        catch
        {
            return null;
        }
    }


public async void IsPilotAuthorized(string sEmployeeNum)
    {
        string dbPilotName = "";
        string dbPassword = "";
        string dbEmployeeNumber = "";
        int dbaccessAllowed = 0;
        int dbPFRID = 0;

        

        ApiService apiServices = new ApiService();
        var userAuthentication = new List<UserAuthentication>(); // = await apiServices.Get(sEmployeeNum);
        userAuthentication = await apiServices.Get("918374");

        userAuthentication[0].PilotName = dbPilotName;   
    }

为清楚起见,请参见所附图片。我创建了一个新项目,并排除了所有不必要的代码。希望对您有所帮助。

enter image description here

解决方法

您可以尝试下面的代码来检查Json结果是数组还是对象。

var response = await client.GetStringAsync("your url")

var token = JToken.Parse(response);

if (token is JArray)
{
   return JsonConvert.DeserializeObject<List<UserAuthentication>>(response)
}
else if (token is JObject)
{
   return JsonConvert.DeserializeObject<UserAuthentication>(response)
}

您可以使用以下代码检查异常。

try{
  ....code
}catch(Exception e){
   Debug.WriteLine(e)
}   

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。