asp.net 中的文件处理程序

本文关键字:处理 程序 文件 net asp | 更新日期: 2023-09-27 18:33:34

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

asp.net 中的文件处理程序

创建一个 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 中应该是这样的

<a href="/GetFile.ashx?id=7" target="_blank">

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 以对所有 PDF 使用您的处理程序:

<httpHandlers>
    <add verb="*" path="*.pdf" type="YourAppName.ServePDF" />
</httpHandlers>

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

<a href="/pdf/Newsletter01.pdf">Download This</a>