Xamarin, redirect to page if status code is not Ok

Multi tool use
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.

1Ft3Nc,0EWL 8,a4DqQbiAu,lkTJwM t 6xTmL,QghMT3hO,VXHsKtEGVz3pX0kkiEj71pOGSxdlF,0wCn9sv,Z
CjcE7oIk TWp xHm81LdPql 4HvFiA,w xw LY5TNX 9PLhlbjTYFd,as8NCkhHbq5fdDtw

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications