在ASP.Net中跟踪文件下载次数/计数

6
有没有一种方法在ASP网站中本质上/手动记录特定文件被访问的次数。例如,我在服务器上有几个.mp3文件,我想知道每个文件被访问了多少次。
跟踪这个的最佳方法是什么?
3个回答

12

是的,有几种方法可以实现这个功能。以下是如何实现:

不要像这样使用直接链接从磁盘服务mp3文件:<a href="http://mysite.com/music/song.mp3"></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=song.mp3">Download Song3.mp3</a>

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

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

遇到了一个问题,但在阅读了这个相关的问题后,它立即得到了解决:https://dev59.com/ekbRa4cB1Zd3GeqPy0lw - Tyler Murry

2
你可以创建一个通用处理程序(*.ashx文件)并通过以下方式访问该文件:

Download.ashx?File=somefile.mp3

在处理程序中,您可以运行代码、记录访问并将文件返回给浏览器。
请确保进行正确的安全检查,因为这可能被用于访问Web目录中的任何文件,甚至整个文件系统!
如果你知道所有的文件都是*.mp3类型,第二个选择是将其添加到web.config文件的httpHandlers部分中。
<add verb="GET" path="*.mp3" type="<reference to your Assembly/HttpHandlerType>" />

在您的 HttpHandler 中运行代码。


1

使用HttpHandler进行下载计数的问题在于每当有人开始下载您的文件时,它都会触发。但是许多互联网蜘蛛、搜索引擎等只会开始下载,很快就会取消!而且他们会注意到您已经下载了文件。

更好的方法是制作一个应用程序来分析您的IIS统计文件。这样,您可以检查用户下载了多少字节。如果字节数与您的文件大小相同或更大,则表示用户已经完整地下载了文件。其他尝试只是尝试。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接