In this article I will explain with an example, how to download Text file(.txt) from URL in ASP.Net Core (.Net Core) Razor Pages.
Note: For beginners in ASP.Net Core (.Net Core 7) razor Pages, please refer my article ASP.Net Core 7 Razor Pages: Hello World Tutorial with Sample Program examples.
 
The Text file will be downloaded from the URL using WebClient class and then will be saved in a Folder (Directory).
 
 

TXT File URL

The following TXT file will be used in this article.
ASP.Net Core Razor Pages: Download Text File (.txt) form URL
 
 

Namespaces

You will need to import the following namespace.
using System.Net;
 
 

Razor PageModel (Code-Behind)

The PageModel consists of following Handler method.

Handler method for handling GET operation

Inside this Handler method, the TXT file is downloaded from the URL using DownloadFile method of the WebClient class.

DownloadFile method

It accepts the following two parameters:
address – The URL of the file to be downloaded.
fileName – Path of the Folder (Directory) where the file will be downloaded.
Note: SecurityProtocol needs to be set to TLS 1.2 (3072) in order to call an API. For more details on SecurityProtocol, please refer my article, Using TLS1.2 in .Net 2.0, .Net 3.0, .Net 3.5 and .Net 4.0.
 
public class IndexModel : PageModel
{
    public void OnGet ()
    {
        ServicePointManager.Expect100Continue = true;
        ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
        WebClient webClient = new WebClient();
        webClient.DownloadFile("https://raw.githubusercontent.com/aspsnippets/test/master/ReadMe.txt", @"D:\Files\ReadMe.txt" );
    }
}
 
 

Razor Page (HTML)

HTML Markup

There is no coding part in Razor Page. Hence, it is skipped.
@page
@model Download_TXT_URL_Core_Razor.IndexModel
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
</body>
</html>
 
 

Screenshot

The downloaded TXT file

ASP.Net Core Razor Pages: Download Text File (.txt) form URL
 
 

Downloads