Xamarin, redirect to page if status code is not Ok

Multi tool use
Xamarin, redirect to page if status code is not Ok
I have REST API that returns if user exists or not by email.
If user exists and I am getting back status OK from API all works fine, but when API response with 404 my app crash. I can't figure out how to check if status is ok or not before app crash and redirect user to register page in case user is not found by API.
Here is code that makes request to 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 Answer
1
You can use below code to identify whether the API call is success or not.
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;
}
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.