httpclient - 服务器在使用 System.Net.Http.HttpClient 时返回无效或无法识别的响应错误

标签 httpclient asp.net-core-2.0 kestrel-http-server .net-core-2.0 kestrel

最近我将我的代码库从 .net core 1.0 迁移到 2.0 。之后,我随机收到错误 “使用 System.Net.Http.HttpClient 时服务器返回无效或无法识别的响应错误”。我在 100 个请求中有 2 个收到此错误。

也如何调试它,因为它是随机发生的:(

程序.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 网络文件
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;
                }
            }
        }
    }

收到错误:

{"ClassName":"Flurl.Http.FlurlHttpException","Message":"GET https://xxx-yyy.oktapreview.com/api/v1/users/00ue1x6pgimMy2Zuf0h7 失败。发送请求时出错。","Data":{},"InnerException":{"ClassName":"System .Net.Http.HttpRequestException", "Message":"发送请求时出错。","Data":{},"InnerException":{"ClassName":"System.Net.Http.WinHttpException", "Message":"服务器返回无效或无法识别的响应","Data":{ },"InnerException":null,"HelpURL":null,"StackTraceString":"在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n 在 System.Threading.Tasks.RendezvousAwaitable 1.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.ConfiguredTaskAwaitable 1.ConfiguredTaskAwaiter.GetResult( )\r\n 在 System.Net.Http.DiagnosticsHandler.d__2.MoveNext()\r\n--- 从上一个抛出异常的位置的堆栈跟踪结束 ---\r\n 在 System.Runtime.ExceptionServices .ExceptionDispatchInfo.Throw()\r\n 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n 在 System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()\r\n 在 System .Net.Http.HttpClient.d__58.MoveNext()\r\n--- 从上一个抛出异常的位置的堆栈跟踪结束---\r\n 在 System.Runtime.Exceptio nServices.ExceptionDispatchInfo.Throw()\r\n 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n 在 Flurl.Http.FlurlRequest.d__19.MoveNext()","RemoteStackTraceString":null,"RemoteStackIndex":0,"ExceptionMethod":null,"HResult":-2147012744,"Source":"System.Private.CoreLib","WatsonBuckets":null},"HelpURL":null}

最佳答案

我遇到了同样的问题并且仍然存在,所以我解决它的解决方案是:将客户端请求块包装在一个 try 中,并在出现错误的情况下进行几次,根据:
https://docs.microsoft.com/en-us/azure/architecture/patterns/retry

关于httpclient - 服务器在使用 System.Net.Http.HttpClient 时返回无效或无法识别的响应错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48884510/

相关文章:

java - 如何使用用户的证书?

client - 如何在 Micronaut 中模拟声明式客户端?

c++ - 替代 URLDownloadToFile 函数

android - 如何制作阻塞的 Android HttpRequest

angular - 无法使用 Angular 5 客户端启动与信号器核心中心的连接

razor - 在没有 Microsoft.NET.Sdk.Web 的情况下使用 Razor

c# - EnumDataType() 属性验证错误消息未显示

reactjs - 同时对 Asp.Net core 2.0 MVC 应用程序 (cookie) 和 REST API (JWT) 进行身份验证

c# - 如何使用 IIS Express 在 ASP.NET Core 中获取控制台输出

c# - 带有 IIS 的 Kestrel - 运行时缺少 libuv.dll