Badboy
Badboy
CC#
Created by Badboy on 3/25/2024 in #help
✅ MAUI on Android - problem with HttpClient Post Method
Hello guys, i am creating this post after more than week of learning and trying to solve it by myself. I have problem with reaching my WebApi with Post Method. There is no problem with Get Method. The error i'm getting is: System.ObjectDisposedException: 'Cannot access a closed Stream.' Which makes literally 0 sense for me. (i dislike that C# took away from us destructors and that may be consequence of it ?) Here is code
public static HttpClientHandler GetInsecureHandler()
{
HttpClientHandler handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
{
if (cert.Issuer.Equals("CN=localhost"))
return true;
return errors == System.Net.Security.SslPolicyErrors.None;
};
return handler;
}



private async Task<int> ConnectToApi_NotWorking()
{
HttpClientHandler insecureHandler = GetInsecureHandler();
HttpClient client = new HttpClient(insecureHandler);
client.Timeout = TimeSpan.FromSeconds(10);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"http://192.168.0.175:5297/api/Login");

request.Headers.Add("accept", "application/json");

request.Content = new StringContent("{\n\"login\":\"a\",\n\"password\":\"a\"\n}");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
await DisplayAlert("AA", responseBody.ToString(), "ok");
return 0;
}
public static HttpClientHandler GetInsecureHandler()
{
HttpClientHandler handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
{
if (cert.Issuer.Equals("CN=localhost"))
return true;
return errors == System.Net.Security.SslPolicyErrors.None;
};
return handler;
}



private async Task<int> ConnectToApi_NotWorking()
{
HttpClientHandler insecureHandler = GetInsecureHandler();
HttpClient client = new HttpClient(insecureHandler);
client.Timeout = TimeSpan.FromSeconds(10);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"http://192.168.0.175:5297/api/Login");

request.Headers.Add("accept", "application/json");

request.Content = new StringContent("{\n\"login\":\"a\",\n\"password\":\"a\"\n}");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
await DisplayAlert("AA", responseBody.ToString(), "ok");
return 0;
}
I will add full git project if needed. There is no problem with implementation of Login in API (tested with same code run on Windows and using Postman)
379 replies