asp.net中的Filehandler

我需要跟踪何时在我的网络应用程序中打开pdf。 现在我正在写一个数据库,当用户点击链接,然后使用后面的代码中的window.open是不理想的,因为Safari阻止弹出窗口和其他Web浏览器在运行时发出警告所以我在想Filehandler是我需要使用的。 我以前没有使用过Filehandler,所以这有用吗? pdf不是二进制forms,它只是一个位于目录中的静态文件。

创建ASHX(比aspx onload事件更快)页面,将文件的id作为查询字符串传递以跟踪每个下载

  public class FileDownload : IHttpHandler { public void ProcessRequest(HttpContext context) { //Track your id string id = context.Request.QueryString["id"]; //save into the database string fileName = "YOUR-FILE.pdf"; context.Response.Clear(); context.Response.ContentType = "application/pdf"; context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); context.Response.TransmitFile(filePath + fileName); context.Response.End(); //download the file } 

在您的HTML中应该是这样的

  

要么

 window.location = "GetFile.ashx?id=7"; 

但我更愿意坚持链接解决方案。

这是一个自定义HttpHandler的选项,它使用PDF的常规锚标记:

创建ASHX(右键单击您的项目 – >添加新项 – >通用处理程序)

 using System.IO; using System.Web; namespace YourAppName { public class ServePDF : IHttpHandler { public void ProcessRequest(HttpContext context) { string fileToServe = context.Request.Path; //Log the user and the file served to the DB FileInfo pdf = new FileInfo(context.Server.MapPath(fileToServe)); context.Response.ClearContent(); context.Response.ContentType = "application/pdf"; context.Response.AddHeader("Content-Disposition", "attachment; filename=" + pdf.Name); context.Response.AddHeader("Content-Length", pdf.Length.ToString()); context.Response.TransmitFile(pdf.FullName); context.Response.Flush(); context.Response.End(); } public bool IsReusable { get { return false; } } } } 

编辑web.config以将Handler用于所有PDF:

    

现在,PDF的常规链接将使用您的处理程序记录活动并提供文件

 Download This