Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

717
Views
Mensaje de error RemoteCertificateNameMismatch/RemoteCertificateChainErrors: crear una aplicación de solicitud de API simple

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:

  1. Conectar al servidor
  2. Enviar clave API para autenticar (configuré mi servidor para habilitar clientes REST sin certificado de cliente)
  3. Obtenga la información JSON del 'Titular de la tarjeta' del servidor
  4. Imprime la información a la Consola.

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(); }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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(); } }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!