giovedì 5 luglio 2007

Nascondere il percorso del download dei file in ASP.NET con C#

Creiamo uno script per gestire download in modo sicuro senza visualizzare il percorso reale del file sul server:

In visual studio creiamo un nuovo sito web:
pagina Default.aspx:

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Pagina senza titolo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
[<a href="#" onclick="javascript:window.open('downloader.aspx?FILEDIPROVA.rar','downloader','');">Download del file con sistema MK</a>]
<br /><br />
[<a href="#" onclick="javascript:window.open('file/downloads/FILEDIPROVA.rar','downloader','');">Download del file tradizionale</a>]
</div>
</form>
</body>
</html>

aggiungiamo una pagina downloader.aspx con codice separato (csharp):

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Download</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
ecco il cs associato:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using MKDEV.CMS;

public partial class downloader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MKFileManager.download(this.Request.QueryString.ToString(), this.Context);
}
}
bene, ora aggiungere la cartella App_Code e creare una Classe MKFileManager.cs:

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;
using System.IO;
namespace MKDEV.CMS
{
public class MKFileManager
{
public MKFileManager()
{

}

public static void download(string filename, HttpContext hc)
{
string path = hc.Server.MapPath("file/downloads/" + filename);
FileInfo file = new FileInfo(path);
if (file.Exists)
{
hc.Response.Clear();
hc.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
hc.Response.AddHeader("Content-Length", file.Length.ToString());
hc.Response.ContentType = "application/octet-stream";
hc.Response.WriteFile(path);
hc.Response.End();
}
else hc.Response.Write("Impossibile avviare il download!");
}
}
}

Salvare il tutto e testate la soluzione.

Ciauz

Nessun commento: