In this article I will explain with an example, how to get JSON data from URL inside Controller’s Action method in ASP.Net Core MVC.
The JSON data will be read from the remote URL using WebClient class in ASP.Net Core MVC.
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"
}
]
Namespaces
You will need to import the following namespace.
Controller
The Controller consists of the following Action method.
Action method for handling GET operation
Inside this Action method, first the JSON string is downloaded from an API using DownloadString method of the WebClient class.
Note: SecurityProtocol needs to be set to TLS 1.2 (3072) in order to call an API.
Finally, the JSON string is returned using the Content function.
public class HomeController : Controller
{
public IActionResult Index()
{
//Fetch the JSON string from URL.
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string json = (new WebClient()).DownloadString("https://raw.githubusercontent.com/aspsnippets/test/master/Customers.json");
//Return the JSON string.
return Content(json);
}
}
Screenshot
Downloads