Search code examples
.netrestssl.net-core

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 POSTMAN\SOAPUI 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;
        }

Solution

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

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