basquang™ on clouds

April 27, 2017

Calling Untrusted SSL HTTPS request using HttpClient give “Message=The remote certificate is invalid according to the validation procedure”

Filed under: JSON,Microsoft Technology,MVC,WebAPI — basquang @ 3:36 PM

Scenario:

+You want to deploy web application server (for example ASP.NET Web API) which require SSL certificate and HTTPS

+You want to make a call to that server using HttpClient

Problem:

+You may see the following errors message when make a call to https required url using HttpClient
HResult=-2146233079
Message=The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

HResult=-2146233087
Message=The remote certificate is invalid according to the validation procedure.

HResult=-2146233088
Message=An error occurred while sending the request.

Solution:

Using this lines of code to accept all server certificates from client. This line of code is using for testing purpose only with you are using self-signed or untrusted certificates

//Accept all server certificate
ServicePointManager.ServerCertificateValidationCallback =
    delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                {
                    return true;
                };

For example you want to make a https POST to Web API method in this post Hello ASP.NET Web API

static async Task PostSampleAsync()
        {
            //Accept all server certificate
            ServicePointManager.ServerCertificateValidationCallback =
                delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                {
                    return true;
                };
            client.BaseAddress = new Uri("https://10.1.16.193/WebAPISample/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.PostAsJsonAsync("api/values", "hello!");
            response.EnsureSuccessStatusCode();
            var result = response.Content.ReadAsAsync<string>().Result;
            Console.WriteLine(result);
        }

Happy coding!

Advertisements

Hello ASP.NET Web API

Filed under: JSON,Microsoft Technology,MVC,WebAPI — basquang @ 3:13 PM

1. Create a simple ASP.NET Web API project with HTTP GET and POST method

Create a simple Web API Controller like this:

    public class ValuesController : ApiController
    {
        string[] list = new string[] { "value1", "value2" };
        // GET api/values
        public IEnumerable<string> Get() { return list; }

        // GET api/values/1
        public string Get(int id) { return list[id]; }

        // POST api/values
        public string Post([FromBody]string value) { return value; }
    }

2. Test the Web API using web browser or POSTMAN

Navigate GET method by web browser

http://localhost:3649/api/values

webapi1

in POSTMAN http://localhost:3649/api/values/1

webapi2

in POSTMAN test HTTP POST method

webapi3

3. Call the Web API using HttpClient

+ Create a console application

+ Install Nuget package

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net452" />
  <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net452" />
</packages>

+ Create a method to consume Web API method GET like this

static HttpClient client = new HttpClient();
        static void Main(string[] args)
        {
            RunAsync().Wait();
        }

        static async Task RunAsync()
        {
            //await PostSampleAsync();
            await GetSampleAsync();

            Console.ReadLine();
        }
static async Task GetSampleAsync()
        {
            // this is where we will send it
            string uri = "http://localhost:3649/api/values";

            // create a request
            HttpWebRequest request = (HttpWebRequest)
            WebRequest.Create(uri); request.KeepAlive = false;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Method = "GET";

            /*====HTTP POST====*/
            //request.Method = "POST";
            //// turn our request string into a byte stream
            //byte[] postBytes = Encoding.ASCII.GetBytes("hello"); //param

            //// this is important - make sure you specify type this way
            //request.ContentType = "application/x-www-form-urlencoded";
            //request.ContentLength = postBytes.Length;
            //Stream requestStream = request.GetRequestStream();

            //// now send it
            //requestStream.Write(postBytes, 0, postBytes.Length);
            //requestStream.Close();

            // grab te response and print it out to the console along with the status code
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
            Console.WriteLine(response.StatusCode);
        }

+ Run debug application you will see the result as below

webapi4

+ Create a method to consume Web API method POST like this

static async Task PostSampleAsync()
        {
            client.BaseAddress = new Uri("http://localhost:3649/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.PostAsJsonAsync("api/values", "hello!");
            response.EnsureSuccessStatusCode();
            var result = response.Content.ReadAsAsync<string>().Result;
            Console.WriteLine(result);
        }

+ Run debug application for this method you will see the result as below

webapi5.PNG

Happy coding!

Create a free website or blog at WordPress.com.