In this article I will explain with an example, how to use WebClient in ASP.Net Core Razor Pages.
This article will illustrate how to call an API using the DownloadString method of the WebClient class in ASP.Net Core Razor Pages.
 
 
ASPSnippets Test API
The following API will be used in this article.
The API returns the following JSON.
[
   {
      "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.
using System.Net;
 
 
Razor PageModel (Code-Behind)
The PageModel consists of the following Handler method.
Handler method for handling GET operation
Inside this Handler method, first the JSON string is downloaded from the 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 set in the Message property.
public class IndexModel : PageModel
{
    public string Message { get; set; }
 
    public void OnGet()
    {
        //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");
        this.Message = json;
    }
}
 
 
Razor Page (HTML)
Inside the HTML of Razor Page, the JSON string is displayed using Message property.
@page
@model WebClient_Razor_Core.Pages.IndexModel
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @Model.Message
</body>
</html>
 
 
Screenshot
Using WebClient in ASP.Net Core Razor Pages
 
 
Downloads