C# ASP.Net中的跟踪文件下载命中率/计数

C# ASP.Net中的跟踪文件下载命中率/计数,c#,asp.net,C#,Asp.net,是否有方法内在/手动记录ASP站点中访问特定文件的次数。例如,我的服务器上有一些.mp3文件,我想知道每个文件被访问了多少次 跟踪此问题的最佳方法是什么?是的,有几种方法。这是你可以做到的 不要使用像这样的直接链接从磁盘提供mp3文件,而是编写HttpHandler来提供文件下载。在HttpHandler中,您可以更新数据库中的文件下载计数 文件下载HttpHandler //your http-handler public class DownloadHandler : IHttpHandle

是否有方法内在/手动记录ASP站点中访问特定文件的次数。例如,我的服务器上有一些.mp3文件,我想知道每个文件被访问了多少次


跟踪此问题的最佳方法是什么?

是的,有几种方法。这是你可以做到的

不要使用像
这样的直接链接从磁盘提供mp3文件,而是编写
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>  

您可以创建一个通用处理程序(*.ashx文件),然后通过以下方式访问该文件:

下载.ashx?File=somefile.mp3

在处理程序中,您可以运行代码、记录访问并将文件返回到浏览器。
确保进行了正确的安全检查,因为这可能用于访问web目录中的任何文件,甚至整个文件系统中的任何文件

如果您知道所有文件都是*.mp3,第二个选项是将其添加到
web.config
文件的
httpHandlers
部分:

<add verb="GET" path="*.mp3" type="<reference to your Assembly/HttpHandlerType>" />


并在您的HttpHandler中运行代码。

使用
HttpHandler
进行下载计数的问题是,每当有人开始下载您的文件时,它就会触发。但是很多网络蜘蛛、搜索引擎等都会刚开始下载,很快就会取消!当他们下载文件时,你们会被注意到


更好的方法是制作一个分析IIS统计文件的应用程序。所以您可以检查用户下载了多少字节。若字节数大于或等于文件大小,则表示用户下载了完整的文件。其他尝试只是尝试。

您的解决方案有问题,但在阅读此相关问题后,问题立即得到解决:
<httpHandlers>
    <add verb="GET" path="*.mp3" type="DownloadHandler"/>
</httpHandlers>
<add verb="GET" path="*.mp3" type="<reference to your Assembly/HttpHandlerType>" />