0

I have a test console-application that is listening for Requests using REST:

Main Method:

static void Main(string[] args)
    {
        var config = new HttpSelfHostConfiguration("https://localhost:8030");

        config.Routes.MapHttpRoute(
            "API Default", "api/{controller}/{id}",
            new { id = RouteParameter.Optional });

        using (HttpSelfHostServer server = new HttpSelfHostServer(config))
        {
            server.OpenAsync().Wait();
            Console.WriteLine("Press Enter to quit.");
            Console.ReadLine();
        }
    }

Controller:

public class RestController : ApiController
{
    [RequireHttps]
    public string Get(int id)
    {
        return "value";
    }
}

And the Overridden RequireHttpsAttribute class. Taken from here

This the code of the application that is listening for requests. So far its working well, but I have some issues with the application that is sending the requests:

Here is the code of the app that calls the hosted REST-Controller:

public class Program
{
    static HttpClient client = new HttpClient();
    static void Main(string[] args)
    {
        SEND();
    }

    public static async void SEND()
    {
        HttpClient lClient = null;

        try
        {

            WebRequestHandler lHandler = new WebRequestHandler();
            X509Certificate lCertificate = GetCert2("localhost");
            lHandler.ClientCertificates.Add(lCertificate);
            lHandler.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
            lHandler.ClientCertificateOptions = ClientCertificateOption.Manual;

            lClient = new HttpClient(lHandler);

            Uri lWebService = new Uri("https://localhost:8030/api/rest/get");

            var requestMessage = new HttpRequestMessage(HttpMethod.Get, lWebService);

            Task<HttpResponseMessage> lRequest = lClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
            HttpResponseMessage lResponse = lRequest.Result;

            HttpStatusCode lStatusCode = lResponse.StatusCode;
            HttpContent lResponseContent = lResponse.Content;

            string lResponseText = await lResponseContent.ReadAsStringAsync();

            if (!lResponse.IsSuccessStatusCode)
            {
                Console.WriteLine("Your Request failed : " + lResponse.ReasonPhrase + ":" + lResponseText);
            }
            else
            {
                Console.WriteLine("Request successful : " + lResponseText);
            }
        }
        catch (Exception pEx)
        {
            Console.WriteLine("Exception occured : " + pEx.Message + " ; " + pEx.InnerException);
        }
    }

    public static bool ValidateServerCertificate(
      object sender,
      X509Certificate certificate,
      X509Chain chain,
      SslPolicyErrors sslPolicyErrors)
    {
        Console.WriteLine("Validating certificate {0}", certificate.Issuer);
        if (sslPolicyErrors == SslPolicyErrors.None)
            return true;

        Console.WriteLine("Certificate error: {0}", sslPolicyErrors);

        // Do not allow this client to communicate with unauthenticated servers.
        return false;
    }
    private static X509Certificate2 GetCert2(string hostname)
    {
        X509Store myX509Store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        myX509Store.Open(OpenFlags.ReadWrite);
        X509Certificate2 myCertificate = myX509Store.Certificates.OfType<X509Certificate2>().FirstOrDefault(cert => cert.GetNameInfo(X509NameType.SimpleName, false) == hostname);
        return myCertificate;
    }

Unfortunately on the line HttpContent lResponseContent = lResponse.Content; the code stops and tells me that the connection has been closed. No further exception details. I suspect that the request is not formatted correctly.

The Code that is getting the certificate is working properly and returns the certificate that I have installed on port 8030...

What am I missing here?

Thank you for your help

Adrian Melzer
  • 159
  • 1
  • 1
  • 9
  • I have now tried to add the security protocol by the following line: `System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;` didnt help at all – Adrian Melzer Sep 26 '18 at 08:24
  • X509Certificate2 myCertificate = myX509Store.Certificates.OfType().FirstOrDefault(cert => cert.GetNameInfo(X509NameType.SimpleName, false) == hostname); ***How to exclude expired certificate ? – Rohit Kanade Aug 27 '19 at 09:15

0 Answers0