I'm learning how API requests work. As part of my learning I am writing a simple app for myself that connects to my company's main app/server through its REST API.
I have some experience with C# and I sort of understand how TCP handshakes work at a very basic level. I have searched through Google and Microsoft's documentation on how to do this and, after seeing so many ways on how people do it differently, I'm at the end of my patience with it.
What I want to do:
- Connect to Server
- Send API Key to authenticate (I have set my server to enable REST clients with no client certificate)
- Get the 'Cardholder' JSON information from the server
- Print the information to the Console.
I'm running the server locally and connect with my 'client' app through port 8904.
When I run my current script in Visual Studio I get an Exception Unhandled error that says: "System.Net.Http.HttpRequestException: 'The SSL connection could not be established, see inner exception... Inner Exception: AuthenticationException: The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch, RemoteCertificateChainErrors
I've tried Googling how to get around this error, which brought me to adding the 'ServicePointManager.ServerCertificateValidationCallback' lines, but they seem to make no difference to the outcome.
Here's my code.
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();
}