ASP.NET下载处理程序适用于IE,但不适用于Chrome

本文关键字:适用于 不适用 Chrome IE ASP 下载 处理 程序 NET | 更新日期: 2023-09-27 18:30:00

我有一个下载处理程序,它会在IE中下载文件,但在chrome中它会尝试自己下载。我的意思是Chrome试图下载一个名为downloadhandler.ashx的文件处理程序的代码是

<%@ WebHandler Language="C#" Class="DownloadHandler" %>
using System;
using System.Web;
public class DownloadHandler : IHttpHandler 
{
public void ProcessRequest(HttpContext context)
{
    string file = "";
    // get the file name from the querystring
    if (context.Request.QueryString["Filepath"] != null)
    {
        file = context.Request.QueryString["Filepath"].ToString();
    }
    string filename = context.Server.MapPath("~/Minutes/" + file);
    System.IO.FileInfo fileInfo = new System.IO.FileInfo(filename);
    try
    {
        if (fileInfo.Exists)
        {
            context.Response.Clear();
            context.Response.AddHeader("Content-Disposition", "inline;attachment; filename='"" + fileInfo.Name + "'"");
            context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            context.Response.ContentType = "application/octet-stream";
            context.Response.TransmitFile(fileInfo.FullName);
            context.Response.Flush();
        }
        else
        {
            throw new Exception("File not found");
        }
    }
    catch (Exception ex)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write(ex.Message);
    }
    finally
    {
        context.Response.End();
    }
}
public bool IsReusable
{
    get
    {
        return false;
    }
}

}

处理程序从这段代码接收信息

private static string BuildAbsolute(string relativeUri)
{
    // get current uri
    Uri uri = HttpContext.Current.Request.Url;
    // build absolute path
    string app = HttpContext.Current.Request.ApplicationPath;
    if (!app.EndsWith("/")) app += "/";
    relativeUri = relativeUri.TrimStart('/');
    // return the absolute path
    return HttpUtility.UrlPathEncode(
      String.Format("http://{0}:{1}{2}{3}",
      uri.Host, uri.Port, app, relativeUri));
}

该方法中使用的

public static string ToDownloadMinutes(string fileName)
{
    return BuildAbsolute(String.Format("Handlers/DownloadHandler.ashx?Filepath={0}", fileName));
}

如果您能在Chrome中使用此下载功能,我们将不胜感激。

ASP.NET下载处理程序适用于IE,但不适用于Chrome

尝试将"inline"从Content Disposition标头中删除为"inline;"附件"不应该一起使用:

context.Response.AddHeader("Content-Disposition", "attachment; filename='""
    + fileInfo.Name + "'"");