Consume webservice protected with a certificate in C#

68 views Asked by At

I need to access the below endpoint from C# (works in my browser where I select the certificate and get the JSON result):

https://s5-certservices.datafordeler.dk/EJERFORTEGNELSE/Ejerfortegnelsen/1/rest/EjerskabMedStamoplysninger?BFEnr=9685073&format=json

I have implemented the below simple C# code to access the endpoint, but get an exception:

An error occurred while sending the request
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)

The code used to access the endpoint:

   internal static HttpResponseMessage CallSB2CertAuthService(string certificateBase64, string certPassword, string serviceFullAddressUri)
    {
        byte[] certBytes = Convert.FromBase64String(certificateBase64);
        var cert = new X509Certificate2(certBytes, certPassword);
        return DoCallSBCertAuthService(cert, serviceFullAddressUri);
    }

    private static HttpResponseMessage DoCallSBCertAuthService(X509Certificate2 cert, string serviceFullAddressUri)
    {
      
        HttpClientHandler handler = new HttpClientHandler();

        handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
        handler.ClientCertificateOptions = ClientCertificateOption.Manual;
        handler.ClientCertificates.Add(cert);
        handler.UseDefaultCredentials = true;


        HttpClient httpClient = new HttpClient(handler);

        try
        {
            HttpResponseMessage response = httpClient.GetAsync("https://s5-certservices.datafordeler.dk/EJERFORTEGNELSE/Ejerfortegnelsen/1/rest/Handelsoplysning?BFEnr=4393252&format=json").Result;
            return response;
        }
        catch (Exception exception)
        {
            return new HttpResponseMessage() { StatusCode = HttpStatusCode.ExpectationFailed, Content = new StringContent(exception.Message.ToString()) };
        }
    }

What could be wrong here?

Full execprion details: Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: {"An error occurred while sending the request."} InnerExceptions: Count = 1 Message: "One or more errors occurred. (An error occurred while sending the request.)" Source: "System.Private.CoreLib" StackTrace: " at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)\r\n at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)\r\n at Core.Helpers.Security.CertUtils.DoCallSBCertAuthService(X509Certificate2 cert, String serviceFullAddressUri) in C:\Core\Helpers\Security\CertUtils.cs:line 38" TargetSite: {Void ThrowIfExceptional(Boolean)}

0

There are 0 answers