In this article I will explain with an example, how to use TLS1.2 with HttpClient in C# and VB.Net.
The ASPSnippets Test REST API
This article uses the following REST API hosted on GitHub.
The JSON string returned from the API
The following JSON string is returned from the ASPSnippets Test API.
[
{
"CustomerId":1,
"Name":"John Hammond",
"Country":"United States"
},
{
"CustomerId":2,
"Name":"Mudassar Khan",
"Country":"India"
},
{
"CustomerId":3,
"Name":"Suzanne Mathews",
"Country":"France"
},
{
"CustomerId":4,
"Name":"Robert Schidner",
"Country":"Russia"
}
]
Public class
The public class consists of the following properties.
C#
public class Customer
{
public string CustomerId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
VB.Net
Public Class Customer
Public Property CustomerId As String
Public Property Name As String
Public Property Country As String
End Sub
Namespaces
You will need to import the following namespaces.
C#
using System.Net;
using System.Net.Http;
using System.Web.Script.Serialization;
VB.Net
Imports System.Net
Imports System.Net.Http
Imports System.Web.Script.Serialization
Using TLS1.2 with HttpClient in C#
Inside the Page Load event handler, first the Security Protocol is set.
Then, the API is called using HttpClient and the JSON string is downloaded and deserialized to Generic List collection of CustomerModel class objects.
protected void Page_Load(object sender, EventArgs e)
{
//Setting TLS 1.2 protocol.
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//Fetch the JSON string from URL.
List<Customer> customers = new List<Customer>();
string apiUrl = "https://raw.githubusercontent.com/aspsnippets/test/master/Customers.json";
HttpClient client = new HttpClient();
HttpResponseMessage response = client.GetAsync(apiUrl).Result;
if (response.IsSuccessStatusCode)
{
customers = new JavaScriptSerializer().Deserialize<List<Customer>>(response.Content.ReadAsStringAsync().Result);
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
'Setting TLS 1.2 protocol.
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
'Fetch the JSON string from URL.
Dim customers As List(Of Customer) = New List(Of Customer)()
Dim apiUrl As String = "https://raw.githubusercontent.com/aspsnippets/test/master/Customers.json"
Dim client As HttpClient = New HttpClient()
Dim response As HttpResponseMessage = client.GetAsync(apiUrl).Result
If response.IsSuccessStatusCode Then
customers = New JavaScriptSerializer().Deserialize(Of List(Of Customer))(response.Content.ReadAsStringAsync().Result)
End If
End Sub
Screenshot
Download