Estoy aprendiendo cómo funcionan las solicitudes de API. Como parte de mi aprendizaje, estoy escribiendo una aplicación simple para mí que se conecta a la aplicación/servidor principal de mi empresa a través de su API REST.
Tengo algo de experiencia con C# y entiendo cómo funcionan los protocolos de enlace TCP en un nivel muy básico. He buscado en la documentación de Google y Microsoft sobre cómo hacer esto y, después de ver tantas formas en que las personas lo hacen de manera diferente, estoy al final de mi paciencia.
Lo que quiero hacer:
Estoy ejecutando el servidor localmente y me conecto con mi aplicación 'cliente' a través del puerto 8904.
Cuando ejecuto mi secuencia de comandos actual en Visual Studio, aparece un error de excepción no controlada que dice: " System.Net.Http.HttpRequestException: 'No se pudo establecer la conexión SSL, consulte la excepción interna... Excepción interna: AuthenticationException: el certificado remoto no es válido según el procedimiento de validación: RemoteCertificateNameMismatch, RemoteCertificateChainErrors
Intenté buscar en Google cómo evitar este error, lo que me llevó a agregar las líneas 'ServicePointManager.ServerCertificateValidationCallback', pero parece que no hacen ninguna diferencia en el resultado.
Aquí está mi código.
static void Main(string[] args) { ConnectToAPI(); } public static void ConnectToAPI () { var client = new HttpClient(); var webRequest = new HttpRequestMessage(HttpMethod.Get, "https://127.0.0.1:8904/api/cardholders"); webRequest.Headers.Add(HttpRequestHeader.Authorization.ToString(), "XXXX-XXXX-XXXX-MY-API-KEY-GOES-HERE"); ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => { return true; }; var response = client.Send(webRequest); using var reader = new StreamReader(webRequest.Content.ReadAsStream()); Console.WriteLine(reader.ReadToEnd()); Console.ReadLine(); }No sé por qué estaba recibiendo este error.
Parecía que podía evitar el error cambiando mi código a esto (ver más abajo).
Si alguien encuentra esto y puede explicar por qué ahora funciona, me ayudará a entender por qué y, con suerte, a alguien más en el futuro también: P
static void Main(string[] args) { ConnectToAPI(); Console.ReadLine(); } public static void ConnectToAPI () { // Creates the WebRequest object using the uri string string uri = String.Format("https://127.0.0.1:8904/api/cardholders"); WebRequest requestObjGet = WebRequest.Create(uri); // Adds API key as a header to the request. Note, must also append 'GGL-API-KEY' to the start requestObjGet.Headers.Add(HttpRequestHeader.Authorization.ToString(), "XXXX-XXXX-XXXX-MY-API-KEY-GOES-HERE"); // Allows you to bypass "AuthenticationException: The remote certificate is invalid according to the validation procedure." error. Don't to do this in production code... ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {return true;}; requestObjGet.Method = "GET"; HttpWebResponse responseObjGet = null; responseObjGet = (HttpWebResponse)requestObjGet.GetResponse(); // String to hold API request response data string strresulttest = null; // Stream reads data to string and prints it to console using (Stream stream = responseObjGet.GetResponseStream()) { StreamReader sr = new StreamReader(stream); strresulttest = sr.ReadToEnd(); Console.WriteLine(strresulttest); sr.Close(); } }