Simple download protection for files and document using ASP.NET / C#

Posted in .NET 2.0 | Authentication | Security at Monday, December 24, 2007 2:36 PM GMT Standard Time
Really really simple. Feel free to write your own custom authentication method to fit your project context.

This is download.aspx:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="download.aspx.cs" Inherits="download" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="" >
<head runat="server">
    <title>Download Page</title>
    <form id="form1" runat="server">

and this is the code behind that file:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class download : System.Web.UI.Page 

    /// Show error to user and close response object.
    private void WriteError(string error) {

    /// Check authentication ticket
    private bool Authenticated() {
        //whatever is a session ticket, membership provider base, container in a coded URL querystring parameters, etc..
        return true;    

    private string GetRepositoryFolder() {
        System.Configuration.AppSettingsReader r = new AppSettingsReader();
        return r.GetValue("RepositoryFolder", typeof(string)).ToString();                

    protected void Page_Load(object sender, EventArgs e)
        if (!Authenticated()){
            WriteError("You are not allowed to download this file");
        else if (Request.QueryString["id"] == null)
            WriteError("Missing parameter : id");
        string filePath = System.IO.Path.Combine(GetRepositoryFolder(),Request.QueryString["id"]);
        System.IO.FileInfo file = new System.IO.FileInfo(filePath);
        if (!file.Exists)
            WriteError("File doesn't exists");
        else {
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/octet-stream";
If successfully authenticated, you will be able to directly download the file:

If not, you will get an error message:

You are not allowed to download this file

AddThis Social Bookmark Button