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

Eld*_*abs 0 api xamarin xamarin.forms

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

如果用户存在并且我从API返回状态确定可以正常工作,但是当API响应时我的应用程序崩溃了.我无法弄清楚如何在应用程序崩溃之前检查状态是否正常,并在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;
Run Code Online (Sandbox Code Playgroud)

Sel*_*och 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;
            }
        }
Run Code Online (Sandbox Code Playgroud)