Xamarin,如果状态代码不正确,则重定向到页面

时间:2018-07-02 04:51:43

标签: api xamarin xamarin.forms

我有REST API,如果用户存在或不存在,则通过电子邮件返回。

如果用户存在并且我从API恢复为OK状态,则一切正常,但是当API响应为404时,我的应用崩溃。我无法弄清楚在应用程序崩溃前如何检查状态是否正常,并在API找不到用户的情况下将用户重定向到注册页面。

以下是向api发出请求的代码:

        string getuserUrl = $"https://localhost:99282/api/users/{email}";

        var client = new HttpClient();

        var uri = new Uri(getuserUrl);

        var result = await client.GetStringAsync(uri);
        var userResult = JsonConvert.DeserializeObject<User>(result);

        return userResult;

1 个答案:

答案 0 :(得分:7)

您可以使用以下代码来识别API调用是否成功。

String URL = "https://localhost:99282/api/users/{email}";
        using (HttpClient client = new HttpClient())
        {
            client.BaseAddress = new Uri(URL);
            try
            {
                HttpResponseMessage response = await client.GetAsync(URL);

                if (response.IsSuccessStatusCode)
                {
                    // Code 200 - If the API call is sucess
                    // You redirect to another page
                }
                else
                {
                    // Show alert for failed calls
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }