The server returned an invalid or unrecognized response error when using System.Net.Http.HttpClient
Asked Answered
T

1

8

Recently i have migrated my code base from .net core 1.0 to 2.0 . After that i am getting the error "The server returned an invalid or unrecognized response error when using System.Net.Http.HttpClient" randomly. I am getting this error in 2 out of 100 requests.

ALso How to debug this since it occurs randomly :(

program.cs

public class Program
    {
        public static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
            .AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(),"hosting.json"), optional: false)
            .Build();

            var useHttps = false;

            bool.TryParse(config !=null  ? config["useHttps"] : "false", out useHttps);

            IWebHost host = null;
            if (useHttps)
            {
                var fileInfo = new FileInfo(config["certName"]);
                X509Certificate2 cert = new X509Certificate2(fileInfo.FullName, config["certPwd"]);

                host = new WebHostBuilder()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseStartup<Startup>()
                    .UseKestrel(options =>
                    {
                        options.Listen(IPAddress.Loopback, 5000);
                        options.Listen(IPAddress.Any, 4430, listenOptions =>
                        {
                            listenOptions.UseHttps(cert);
                        });
                    })
                    .UseIISIntegration()
                    .Build();
            }
            else
            {
                host = new WebHostBuilder()
                    .UseStartup<Startup>()
                    .UseKestrel()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseIISIntegration()
                    .UseUrls(config["url"])
                    .Build();

            }
            host.Run();


        }
    }

HTTP network file

public class NetworkExtensions
    {
        public static IConfiguration Configuration { get; set; }
        public static ILogger Log { get; set; }

        /// <summary>
        /// Flurl to get api
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="requestDto"></param> 
        /// <param name="rateLimit">This param is used to Perform OKTA api Retry </param> 
        /// <returns></returns>
        public static async Task<T> Get<T>(OktaRequestDto requestDto, OKTARateLimit rateLimit = null)
        {
            using (MiniProfiler.Current.Step("Okta : Get"))
            {

                // OKTA code execution starts here.
                string url = requestDto.BaseUrl
                    .AppendPathSegment(requestDto.ApiName + requestDto.Query);

                // Handle all querystring append.
                if (requestDto.QueryStrings != null && requestDto.QueryStrings.Count > 0)
                {
                    foreach (var querystring in requestDto.QueryStrings.Keys)
                    {
                        //FLURL is encoding the value, To ensure the value is passed correct, added true param to stop default behavior
                        url = url.SetQueryParam(querystring, requestDto.QueryStrings[querystring], true);
                    }
                }

                var response = await url.WithHeader("Authorization", requestDto.ApiKey).GetJsonAsync<T>();


                Log.Information("response  => " + JsonConvert.SerializeObject(response));

                return response;

                catch (FlurlHttpException ex)
                {
                    // there is an OKTA exception, return the default value, The exception is captured in the FLURLConfig
                    OneLoginException ole = new OneLoginException(ex, requestDto);
                    throw ole;

                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }

Error received:

{"ClassName":"Flurl.Http.FlurlHttpException","Message":"GET https://xxx-yyy.oktapreview.com/api/v1/users/00ue1x6pgimMy2Zuf0h7 failed. An error occurred while sending the request.","Data":{},"InnerException":{"ClassName":"System.Net.Http.HttpRequestException","Message":"An error occurred while sending the request.","Data":{},"InnerException":{"ClassName":"System.Net.Http.WinHttpException","Message":"The server returned an invalid or unrecognized response","Data":{},"InnerException":null,"HelpURL":null,"StackTraceString":" at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Threading.Tasks.RendezvousAwaitable1.GetResult()\r\n at System.Net.Http.WinHttpHandler.<StartRequest>d__105.MoveNext()","RemoteStackTraceString":null,"RemoteStackIndex":0,"ExceptionMethod":null,"HResult":-2147012744,"Source":"System.Private.CoreLib","WatsonBuckets":null,"NativeErrorCode":12152},"HelpURL":null,"StackTraceString":" at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()\r\n at System.Net.Http.DiagnosticsHandler.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()\r\n at System.Net.Http.HttpClient.d__58.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Flurl.Http.FlurlRequest.d__19.MoveNext()","RemoteStackTraceString":null,"RemoteStackIndex":0,"ExceptionMethod":null,"HResult":-2147012744,"Source":"System.Private.CoreLib","WatsonBuckets":null},"HelpURL":null}

Typescript answered 20/2, 2018 at 11:40 Comment(1)
Were you able to solve this?Heiress
P
0

I was getting the same problem and still do, so my solution to work around it is: wrap the client request block within a try and make it few times in case of error, according to: https://learn.microsoft.com/en-us/azure/architecture/patterns/retry

Peyote answered 16/11, 2020 at 12:23 Comment(2)
Could you provide a code example of how to do this please?Pyrethrin
public async static Task<string> HttpRequestToURL(string url) { string responseContent = ""; bool ok = false; int tries = 1; while (tries < 7 && !ok) try { responseContent = await client.GetStringAsync(url); ok = true; } catch (Exception ex) { tries++; Debug.WriteLine("[HttpRequestToURL]" + ex.Message); Thread.Sleep(new Random().Next(100, 250) * tries); } return responseContent; }Peyote

© 2022 - 2024 — McMap. All rights reserved.