Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

REST API Call Failing in .NET Core (All version), working in .NET framework

This below code is working in .NET Frameworks (4.5 - 4.8). But it's failing in all versions of .NET Core with a message "The message received was unexpected or badly formatted". I have tried with all SSL Protocols.

I am using a console app and Core app is not having any extra packages. I am also using same OS, same VS 2019 in same system for both .NET framework and .NET core. It's working with POSTMANSOAPUI as well.

private static void GetPackage()
        {
            var _clientHandler = new HttpClientHandler();
            _clientHandler.ClientCertificates.Add(GetClientCertificate());

            using (var client = new HttpClient(_clientHandler, true))
            {
                client.BaseAddress = new Uri("<TIBCO URL>");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "<token>");
                client.DefaultRequestHeaders.Add("YYYYYYY", "YYYYY");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var res = client.GetAsync("<path>");

                try
                {
                    using (var content = res.Result.Content)
                    {
                        var result = content.ReadAsStringAsync();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.InnerException?.InnerException?.InnerException?.Message); //output of this line is "The message received was unexpected or badly formatted"
                    Console.WriteLine(e.ToString());
                }
            }
        }

        private static X509Certificate2 GetClientCertificate()
        {
            var certFile = Path.Combine(@"C:<path>", "<Name>");
            X509Certificate2 certificate = new X509Certificate2(certFile, "<passowrd>");
            return certificate;
        }
question from:https://stackoverflow.com/questions/66052466/rest-api-call-failing-in-net-core-all-version-working-in-net-framework

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I have changed HttpClientHandler class to SocketsHttpHandler class. It's working not in .NET Core.

https://docs.microsoft.com/en-us/dotnet/api/system.net.http.socketshttphandler?view=net-5.0


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...