用户点击一个按钮后,我希望下载一个文件.我try 了以下似乎有效的方法,但没有抛出一个不可接受的异常(ThreadAbort).

    System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
    response.ClearContent();
    response.Clear();
    response.ContentType = "text/plain";
    response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
    response.TransmitFile(Server.MapPath("FileDownload.csv"));
    response.Flush();
    response.End();  

推荐答案

您可以使用HTTP处理程序(.ashx)下载文件,如下所示:

DownloadFile.ashx:

public class DownloadFile : IHttpHandler 
{
    public void ProcessRequest(HttpContext context)
    {   
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        response.Clear();
        response.ContentType = "text/plain";
        response.AddHeader("Content-Disposition", 
                           "attachment; filename=" + fileName + ";");
        response.TransmitFile(Server.MapPath("FileDownload.csv"));
        response.Flush();    
        response.End();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

然后可以从按钮单击事件处理程序调用HTTP处理程序,如下所示:

标记:

<asp:Button ID="btnDownload" runat="server" Text="Download File" 
            OnClick="btnDownload_Click"/>

代码隐藏:

protected void btnDownload_Click(object sender, EventArgs e)
{
    Response.Redirect("PathToHttpHandler/DownloadFile.ashx");
}

Passing a parameter to the HTTP Handler:

您只需将查询字符串变量附加到Response.Redirect(),如下所示:

Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");

然后在实际的处理程序代码中,可以使用HttpContext中的Request对象来获取查询字符串变量值,如下所示:

System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];

// Use the yourVariableValue here

Note-通常将文件名作为查询字符串参数传递给用户,以建议用户该文件实际是什么,在这种情况下,他们可以用另存为.覆盖该Name值.

Asp.net相关问答推荐

无法翻译 LINQ

在哪里可以记录 ASP.NET Core 应用程序的启动/停止/错误事件?

如何在 ASP.NET 中使用时区?

加载特定 UpdatePanel 后如何调用客户端 javascript 函数

解析器错误消息:无法加载类型sometype

防止 asp.net Web 表单中的跨站点请求伪造 (csrf) 攻击

带有邮箱地址参数的 WebApi 方法从 HttpClient 返回 404

更改后未应用 CSS

是否可以在 web.config 中添加响应 http 标头?

为 ASP.NET Core MVC 显示 404 Not Found 页面

@(at) 登录文件路径/字符串

禁用 web.config 继承?

通过 ASP.NET/C# 使用 Plupload

SQLServer 与 StateServer 的 ASP.NET 会话状态性能

Cache.Add 绝对过期 - 是否基于 UTC?

如何将 GridView.DataSource 导出到数据表或数据集?

获取 POST 变量

使用 jQuery 从 asp:RadioButtonList 读取选定的值

如何使用 WebAPI 处理图像

获取 Application_Start 中的当前应用程序物理路径