如何使用ASP.NET跟踪下载?

如何使用ASP.NET跟踪下载?

我想找到有多少用户完成了文件下载?

另外如何限制用户使用特定的IP?

例如,如果用户下载http://example.com/file.exe ,则该轨道将自动运行。

如果您想从您的网站计算下载量,请创建下载页面并计算请求数:

文件链接应该类似于Download.aspx?file=123

 protected void Page_Load(object sender, EventArgs e) { int id; if (Int32.TryParse(Request.QueryString["file"], out id)) { Count(id); // increment the counter GetFile(id); // go to db or xml file to determine which file return to user } } 

或者Download.aspx?file=/files/file1.exe

 protected void Page_Load(object sender, EventArgs e) { FileInfo info = new FileInfo(Server.MapPath(Request.QueryString["file"])); if (info.Exists) { Count(info.Name); GetFile(info.FullName); } } 

要限制对“下载”页面的访问:

 protected void Page_Init(object sender, EventArgs e) { string ip = this.Request.UserHostAddress; if (ip != 127.0.0.1) { context.Response.StatusCode = 403; // forbidden } } 

有几种方法可以做到这一点。 这是你如何做到这一点。

不是使用类的直接链接从磁盘提供文件,而是编写一个HttpHandler来提供文件下载。 在HttpHandler中,您可以更新数据库中的file-download-count。

文件下载HttpHandler

 //your http-handler public class DownloadHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { string fileName = context.Request.QueryString["filename"].ToString(); string filePath = "path of the file on disk"; //you know where your files are FileInfo file = new System.IO.FileInfo(filePath); if (file.Exists) { try { //increment this file download count into database here. } catch (Exception) { //handle the situation gracefully. } //return the file context.Response.Clear(); context.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); context.Response.AddHeader("Content-Length", file.Length.ToString()); context.Response.ContentType = "application/octet-stream"; context.Response.WriteFile(file.FullName); context.ApplicationInstance.CompleteRequest(); context.Response.End(); } } public bool IsReusable { get { return true; } } } 

Web.config配置

 //httphandle configuration in your web.config    

链接前端的文件下载

 //in your front-end website pages, html,aspx,php whatever. Download file.exe 

此外 ,您可以将web.config中的exe扩展名映射到HttpHandler。 要做到这一点,你必须确保,你配置你的IIS将.exe扩展请求转发到asp.net工作进程而不是直接服务,并确保mp3文件不在处理程序捕获的同一位置,如果在同一位置的磁盘上找到该文件,则HttpHandler将被覆盖,并且该文件将从磁盘提供。

    

使用HttpHandler下载部分。 例如,您可以使用OutputStream 。 调用此处理程序时,您可以更新数据库中的计数器。

另外如何限制用户使用特定的IP?

为此你可以使用HttpModule:看看这些样本 。