0

I'm attempting to directly retrieve the SSL certificate for a given domain, so that I can access its fields (such as Issuer, Expiration date, Errors, etc).

All the non-deprecated examples I can find, including from Microsoft, make use of the ServerCertificateCustomValidationCallback method, such as in the example here: https://learn.microsoft.com/en-us/dotnet/api/System.Net.Http.HttpClientHandler.ServerCertificateCustomValidationCallback?view=net-7.0

The issue is that I want to sequentially execute my code as follows, without relying on any callback function in a separate thread. What I want is for example the following:

...
var cert = await httpClient.SomehowRequestCertificateFromUrl("https://someUrl.com"/);
Console.WriteLine($"The issuer is: {cert.issuer}");

Essentially I want to maintain the same scope at the point I make the request and receive the response, awaiting for the operation to complete. Using the callback method that's typically used, I lose the scope. I don't wish to store the certificate anywhere, I merely want to examine the certificate response from a request within the same scope. Is there any way to achieve what I want?

For reference, I'm creating a .Net Core console application, not using Asp.Net, so I have no need for a callback, and a callback goes against what I want to do.

user4779
  • 645
  • 5
  • 14
  • 1
    You should be able to use `TaskCompletionSource` in a pattern [like this](https://learn.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/interop-with-other-asynchronous-patterns-and-types#tasks-and-the-event-based-asynchronous-pattern-eap) to get the certificate using an await-compatible API. However, it is likely that the client will dispose the certificate, so YMMV. – Stephen Cleary Feb 02 '23 at 11:53
  • @StephenCleary Thanks this works. In hindsight its simply a matter of registering a lambda as the callback within the same scope, hence all variables can be shared from outside it. I should have realized something so simple. The problem is making the HttpClient reusable, which Ive done by making the TaskCompletionSource a global property which the callback simply sets the value for, the wrapper function then await's this global property, returns the result, and resets it again. There might be a more elegant solution, but I can confirm this works in terms of my pseudocode doing exactly as asked – user4779 Feb 03 '23 at 07:08

0 Answers0