Cannot access a closed stream

Stesvis 1,041 Reputation points
2021-10-15T16:08:22.133+00:00

I am noticing lots of httpclient errors in my app.
This one says: System.ObjectDisposedException: Cannot access a closed Stream

// App.xaml.cs
private static HttpClient _myHttpClient;
public static HttpClient MyHttpClient
{
    get
    {
        if (_myHttpClient == null)
        {
            _myHttpClient = new HttpClient()
            {
                Timeout = TimeSpan.FromSeconds(120),
                BaseAddress = new Uri(ApiUrlsBase.BaseUrl),
            };

            _myHttpClient.DefaultRequestHeaders.Add(CustomRequestHeaders.ApiVersion, "2");
        }

        return _myHttpClient;
    }
}

// HttpService.cs
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

var payload = JsonConvert.SerializeObject(postData, Formatting.Indented);
var postContent = new StringContent(payload, Encoding.UTF8, "application/json");
var response = await MyHttpClient.PostAsync(url, postContent); // this line threw the exception

Of course this only happens sometimes, very randomly.
What could it be? Any way to track it down or prevent it?

Developer technologies .NET Xamarin
Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2021-10-18T14:52:25.907+00:00

    You may need to check the logs on the server you are calling.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.