【发布时间】:2010-07-01 03:10:13
【问题描述】:
有没有办法在 ASP 站点中固有/手动记录特定文件的访问次数。例如,我的服务器上有几个 .mp3 文件,我想知道每个文件被访问了多少次。
跟踪这个的最佳方法是什么?
【问题讨论】:
有没有办法在 ASP 站点中固有/手动记录特定文件的访问次数。例如,我的服务器上有几个 .mp3 文件,我想知道每个文件被访问了多少次。
跟踪这个的最佳方法是什么?
【问题讨论】:
是的,有几种方法可以做到这一点。以下是您可以这样做的方法。
不要使用像<a href="http://mysite.com/music/song.mp3"></a> 这样的直接链接从磁盘提供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>
从前端链接文件下载
//in your front-end website pages, html,aspx,php whatever.
<a href="FileDownload.ashx?filename=song.mp3">Download Song3.mp3</a>
另外,您可以将 web.config 中的 mp3extension 映射到 HttpHandler。为此,您必须确保将 IIS 配置为将 .mp3 扩展请求转发到 asp.net 工作进程而不是直接提供服务,并确保 mp3 文件不在处理程序捕获的同一位置,如果文件在磁盘上的同一位置找到,则 HttpHandler 将被覆盖,文件将从磁盘提供。
<httpHandlers>
<add verb="GET" path="*.mp3" type="DownloadHandler"/>
</httpHandlers>
【讨论】:
您可以做的是创建一个通用处理程序(*.ashx 文件),然后通过以下方式访问该文件:
下载.ashx?File=somefile.mp3
在处理程序中,您可以运行代码、记录访问并将文件返回到浏览器。
确保您进行了正确的安全检查,因为这可能会被用来访问您网络目录中的任何文件甚至在整个文件系统上!
如果您知道所有文件都是 *.mp3,则第二种选择是将其添加到 web.config 文件的 httpHandlers 部分:
<add verb="GET" path="*.mp3" type="<reference to your Assembly/HttpHandlerType>" />
并在您的 HttpHandler 中运行代码。
【讨论】:
使用HttpHandler 进行下载计数的问题是它会在有人开始下载您的文件时触发。但是很多网络蜘蛛、搜索引擎等都是刚开始下载,很快就取消了!当他们下载文件时,您会注意到。
更好的方法是制作一个分析 IIS 统计文件的应用程序。所以你可以检查用户下载了多少字节。如果字节与您的文件大小相同或更大,则表示用户下载了完整的文件。其他尝试只是尝试。
【讨论】: