简体   繁体   中英

.NET Core HttpClient - “A security error occurred” HttpRequestException

Using .NET Core and C# I'm trying to make an HTTPS request to my Vizio TV, the API is somewhat documented here .

When visiting the HTTP server in Chrome I receive a "NET::ERR_CERT_AUTHORITY_INVALID" error. When I make the request in C# with a HttpClient , a HttpRequestException is thrown. I've tried adding the certificate to Windows but I'm just not familiar enough with TLS.

I'm also not concerned about my communications being snooped on so I would like to just ignore any HTTPS errors.

Here's the relevant code I'm working with.

public async Task Pair(string deviceName) {
    using (var httpClient = new HttpClient())
    try {
        httpClient.BaseAddress = new Uri($"https://{televisionIPAddress}:9000/");

        // Assume all certificates are valid?
        ServicePointManager.ServerCertificateValidationCallback =
            (sender, certificate, chain, sslPolicyErrors) => true;

        deviceID = Guid.NewGuid().ToString();

        var startPairingRequest = new HttpRequestMessage(HttpMethod.Put, "/pairing/start");
        startPairingRequest.Content = CreateStringContent(new PairingStartRequestBody {
            DeviceID = deviceID,
            DeviceName = deviceName
        });

        var startPairingResponse = await httpClient.SendAsync(startPairingRequest); // HttpRequestException thrown here
        Console.WriteLine(startPairingResponse);
    } catch (HttpRequestException e) {
        Console.WriteLine(e.InnerException.Message); // prints "A security error occurred"
    }
}

StringContent CreateStringContent(object obj) {
    return new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
}

Resolved the issue by setting up a HttpClientHandler and setting ServerCertificateCustomValidationCallback to return true.

using (var handler = new HttpClientHandler {
    ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
})
using (var httpClient = new HttpClient(handler))

Too late for the party here, but if you are looking for .net core solution then please try the below code

using (var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true })
        {
            using (var httpClient = new HttpClient(handler))
            {
                //your business logic goes here
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM