'How to restrict a download in asp.net web forms?

I have this code in the page_load method of an ASP.NET .aspx page that downloads a particular file from the same web site:

System.IO.FileInfo file = new System.IO.FileInfo(filePath);

if (file.Exists)
{
    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + newFileName);
    Response.AddHeader("Content-Length", file.Length.ToString());
    Response.ContentType = "application/octet-stream";    
    Response.WriteFile(filePath);
    Response.Flush();
    Response.End();
}

I only want to allow a download if it comes from a clickable link on any page from my own second domain xx.com. All other download attempts coming from other web sites or a direct download need to be disallowed.

How can I detect these download attempts in page_load and allow or disallow the download?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source