Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everybody,
Iam developing a Maui.Net app for login to WebApi
Iam getting the error (Can not access closed stream) in android when posting data to api
this is my code
public async Task<UserResponse> Login(string username, string password)
{
	var userInfo = new UserResponse();
	var client = new HttpClient();
	string url = "http://marriedJudgeApi.goldenrayah.com/User/Authenticate";
	client.BaseAddress = new Uri(url);

	var loginDto = new LoginDto(username, password);
	var json = JsonConvert.SerializeObject(loginDto);
	var data = new StringContent(json, Encoding.UTF8, "application/json");

	HttpResponseMessage response = await client.PostAsync(url, data);
	if (response.IsSuccessStatusCode)
	{
		string content = response.Content.ReadAsStringAsync().Result;
		userInfo = JsonConvert.DeserializeObject<UserResponse>(content);
		return userInfo;
	}
	else
	{
		return null;
	}
}


What I have tried:

I have tried put the HttpClint declaration outside then function
Posted
Updated 21-Feb-23 13:38pm
Comments
Richard Deeming 22-Feb-23 10:25am    
string content = response.Content.ReadAsStringAsync().Result;

Why?! You're in an async method, so calling .Result on a task-returning method is never correct. Just await the task!
string content = await response.Content.ReadAsStringAsync();

1 solution

you could use this new feature released today for VS2022 v17.5: API development inner-loop - Visual Studio 2022 - 17.5 Released - Visual Studio Blog[^] ... it should help debug this issue.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900