Getting error "The Response ended prematurely" while using "HttpClient" and "IHttpClientFactory" in .NetStandard2.0

86 Views Asked by At

I have a .netstandard2.0 class library.This is consuming by a .netframework 4.7.2 web api as DLL. We have tried below static httpclient But I'm getting

"The Response ended prematurely"

(This is the inner most exception). Not getting for all request, average 50 in an hour.


    public class Helper 
    {
        private static readonly HttpClient _httpClient = new HttpClient(new HttpClientHandler() { AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate })
        {
            Timeout = TimeSpan.FromSeconds(15)
        };

        public async Task<string> ProviderCallAsync(string url, string Request, string AccessToken, HttpMethod HttpMethod)
        {
            string ProviderResponse = "";
            try
            {
                if (HttpMethod == HttpMethod.Get)
                {
                    url = url + Request;
                }
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod, url);
                if (HttpMethod != HttpMethod.Get)
                {
                    request.Content = new StringContent(Request, Encoding.UTF8, "application/json-patch+json");
                }
                if (!string.IsNullOrWhiteSpace(AccessToken))
                {
                    request.Headers.Add("Authorization", "Bearer " + AccessToken);
                }
                request.Headers.Add("Accept-Encoding", "gzip, deflate");
                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
                ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls;
                HttpResponseMessage response = await _httpClient.SendAsync(request);

                ProviderResponse = await response?.Content?.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
            }
            return ProviderResponse;
        }
    }

I have also tried with IhttpClientFactory like below, I have implemented like this as it is a class library and not don't have Startup.CS. Got same exception

public class Helper 
{
        private static readonly object Instancelock = new object();
        private readonly IHttpClientFactory _httpClientFactory = GetHttpClientFactory();
        private static IServiceProvider serviceProvider { get; set; }

        public static void Initialize()
        {
            if (serviceProvider == null)
            {
                lock (Instancelock)
                {
                    if (serviceProvider == null)
                    {
                        var services = new ServiceCollection();
                        services.AddHttpClient("HttpClient", client =>
                        {
                            client.Timeout = TimeSpan.FromSeconds(15);
                        }).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
                        {
                            AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate,
                            SslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls

                        }).SetHandlerLifetime(TimeSpan.FromMinutes(1));
                        serviceProvider = services.BuildServiceProvider();
                    }
                }
            }
        }

        public static IHttpClientFactory GetHttpClientFactory()
        {
            if (serviceProvider == null)
            {
                Initialize();
            }
            return (IHttpClientFactory)serviceProvider.GetServices<IHttpClientFactory>().First();
        }
        public async Task<string> ProviderCallAsync(string url, string Request, string AccessToken, HttpMethod HttpMethod, [System.Runtime.CompilerServices.CallerMemberName] string CallerMemberName = "", [System.Runtime.CompilerServices.CallerFilePath] string CallerFilePath = "")
        {
            string ProviderResponse = "";
            try
            {
                if (HttpMethod == HttpMethod.Get)
                {
                    url = url + Request;
                }
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod, url);
                if (HttpMethod != HttpMethod.Get)
                {
                    request.Content = new StringContent(Request, Encoding.UTF8, "application/json-patch+json");
                }

                if (!string.IsNullOrWhiteSpace(AccessToken))
                {
                    request.Headers.Add("Authorization", "Bearer " + AccessToken);
                }

                request.Headers.Add("Accept-Encoding", "gzip, deflate");
                var httpClient = _httpClientFactory.CreateClient("HttpClient");
                using (var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
                {
                    ProviderResponse = await response?.Content?.ReadAsStringAsync();
                }

            }
            catch (Exception ex)
            {

            }
            return ProviderResponse;
        }
    }
0

There are 0 best solutions below