gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:58:12 25 4
gpt4 key购买 nike

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

我想知道有多少用户完成了文件下载?

还有如何限制用户访问特定 IP?

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

最佳答案

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

而不是使用像 <a href="http://mysite.com/music/file.exe"></a> 这样的直接链接从磁盘提供文件, 写一个 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>

前端链接文件下载

//in your front-end website pages, html,aspx,php whatever.
<a href="FileDownload.ashx?filename=file.exe">Download file.exe</a>

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

<httpHandlers>
<add verb="GET" path="*.exe" type="DownloadHandler"/>
</httpHandlers>

关于c# - 如何使用 ASP.NET 跟踪下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3386825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com