Question

I have set up a simple Web API project, that enforces https,

IIS express configuration

When I call a service form my browser, I get a correct result:

enter image description here

But how do I call this service from a WPF client?

Calling the 'non' https service does not give me any problem:

HttpClient client = new HttpClient() 
{
    BaseAddress = new Uri("http://localhost:49838/") 
};

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

try
{
     HttpResponseMessage response = await client.GetAsync("/api/products/");
     ...

How do I call my https://... service?

Was it helpful?

Solution

I know you have already solved your problem. Bur I am answering just to update you and other new users, that they should use HttpClient class and not WebRequest.

Read more about HTTPClient - HttpClient is Here!

HttpClient is more powerfull and improved tool. HttpClient is a modern HTTP client for .NET. It provides a flexible and extensible API for accessing all things exposed through HTTP.

Here is the sample method that will check certificate from Trusted Root Certification Authority (StoreName.Root) and it will check certificates in your local machine ( StoreLocation.LocalMachine).

        X509Certificate2 cert = null;
        X509Store store = null;

        try
        {
            store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
            // You can check certificate here ... 
            // and populate cert variable.. 
        }
        finally
        {
            if (store != null) store.Close();
        }


        var clientHandler = new WebRequestHandler();
        if (cert != null) clientHandler.ClientCertificates.Add(cert);

        var client = new HttpClient(clientHandler) {BaseAddress = new Uri(uri)};

And then you can do whatever you want to do .

Hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top