In this article I will explain with an example, how to use TLS 1.2 Security Protocol with HttpClient in ASP.Net Core MVC.
This article will illustrate how to call a JSON REST API using HttpClient and also how to deserialize JSON data to object in ASP.Net Core MVC.
Note: For beginners in ASP.Net Core (.Net Core 7), please refer my article ASP.Net Core 7: Hello World Tutorial with Sample Program example.
 
 

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"
  }
]
 
 

Model

The Model class consists of following properties.
public class CustomerModel
{
    public string CustomerId { getset; }
    public string Name { getset; }
    public string Country { getset; }
}
 
 

Namespaces

You will need to import the following namespaces.
using System.Net;
using Newtonsoft.Json;
 
 

Controller

The Controller consists of the following Action method.

Action method for handling GET operation

Inside this Action method, first the Security Protocol is set.
Note: For previous .Net Framework versions, please refer Using TLS1.2 in .Net 2.0, .Net 3.0, .Net 3.5 and .Net 4.0.
 
Then, the API is called using HttpClient and the JSON string is downloaded and deserialized to Generic List collection of CustomerModel class objects using DeserializeObject method of JsonConvert class.
Finally, a Generic List collection of CustomerModel class object is returned.
public class HomeController : Controller
{
    public IActionResult Index()
    {
        //Setting TLS 1.2 protocol
        ServicePointManager.Expect100Continue = true;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
 
        //Fetch the JSON string from URL.
        List<CustomerModel> customers = new List<CustomerModel>();
        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 = JsonConvert.DeserializeObject<List<CustomerModel>>(response.Content.ReadAsStringAsync().Result);
        }
 
        //Return the Deserialized JSON object.
        return Json(customers);
    }
}
 
 

Screenshot

.Net Core TLS 1.2: Using TLS 1.2 in ASP.Net Core
 
 

Downloads