Unhandled Exception on iOS Devices due to HttpClient [Xamarin.Forms (Mobile Blazor Bindings)]
Hello
I've made an hybrid mobile application using Mobile Blazor Bindings (which is based on Xamarin Forms). It's on production but since the it's deployed I'm having a problem with iOS platform.
At first problems arose on login procedure
public async Task Login(LoginRequest loginRequest)
{
var result = await _httpClient.PostAsJsonAsync("api/auth/login", loginRequest);
if (result.StatusCode == System.Net.HttpStatusCode.BadRequest) throw new Exception(await result.Content.ReadAsStringAsync());
result.EnsureSuccessStatusCode();
}
This code snippet is the method called by AuthService on client side. Throwing an exception resulted "Unhandled Exception" on -some- iOS Devices. I haven't been able to reproduce the same error on both iPhoneSimulator (iOS 14.4) and my iPhone 5S (iOS 12.5.1)
So to "kinda" fix it I change the method a little bit:
public async Task<HttpResponseMessage> Login(LoginRequest loginRequest)
{
var result = await _httpClient.PostAsJsonAsync("api/auth/Login", loginRequest);
if (result.IsSuccessStatusCode)
{
return result; //result.EnsureSuccessStatusCode();
}
return new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.BadRequest };
}
I also had the same problem with EnsureSuccessStatusCode so I deleted it too.
And this is the State Provider which calls this method:
public async Task<int> Login(LoginRequest loginParameters)
{
var result = await api.Login(loginParameters);
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
return 0;
}
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
return 1;
}
This solved my problem at login page but now I can't login due to another "Unhandled Exception" which says "Unhandled Exception", Response Status code does not indicate success: 404 (Not Found).
How is this possible? I can access to my API on all clients but only on some iOS devices it can't handle the API Requests.
A friend of my suggested to me that maybe the way I define my HttpClient causing the problem.
public static HttpClient _http = new HttpClient() { BaseAddress = new Uri("http://api.xxxxx.com") };
This is how I defined it. Does it matter if it was new Uri("http://api.xxxxx.com")
or new Uri("http://api.xxxxx.com/")
or when I 'm calling the PostAsJsonAsync for example should it be like this _httpClient.PostAsJsonAsync("api/auth/Login", loginRequest);
or this _httpClient.PostAsJsonAsync("/api/auth/Login", loginRequest);
which one is the right way if that even matters?