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?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,294 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,247 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,021 Reputation points
    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