C# 如何使用ASP.NET跟踪下载?
如何使用ASP.NET跟踪下载 我想知道有多少用户完成了文件下载 又如何才能使特定IP限制用户C# 如何使用ASP.NET跟踪下载?,c#,asp.net,download,C#,Asp.net,Download,如何使用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(Re
例如,如果用户下载
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。例如,您可以使用。调用此处理程序时,可以更新数据库中的计数器 又如何才能使特定IP限制用户
为此,您可以使用。有几种方法。这是你可以做到的 不要使用像
这样的直接链接从磁盘提供文件,而是编写HttpHandler
来提供文件下载。在HttpHandler中,您可以更新数据库中的文件下载计数
文件下载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
<httpHandlers>
<add verb="GET" path="FileDownload.ashx" type="DownloadHandler"/>
</httpHandlers>
“我想跟踪直接链接,而不是重定向的项目,这可能是重复的。@佩德拉姆:跟踪从本地服务器下载的内容?谢谢,但我真的需要直接链接吗?”?我不能真正使用FileDownload.ashx?filename=file.exe。请将exe扩展名映射到asp.net。请阅读文章的最后一部分。
//in your front-end website pages, html,aspx,php whatever.
<a href="FileDownload.ashx?filename=file.exe">Download file.exe</a>
<httpHandlers>
<add verb="GET" path="*.exe" type="DownloadHandler"/>
</httpHandlers>