C# ASP。 NET 内联文件下载处理程序

C# ASP. NET Inline file download handler

我正在尝试创建一个文件处理程序,供用户在网页上单击文件名时下载文件。我已经实施了几次没有问题,但我目前遇到了一个我无法理解的错误。

代码:

protected void btnViewFile_Click(object sender, EventArgs e)
{
    var btnViewFile = sender as LinkButton;
    Response.Clear();
    Response.ContentType = "application/octet-stream";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + btnViewFile.CommandArgument.ToString());
    Response.WriteFile(Server.MapPath(btnViewFile.CommandArgument));
    Response.End();
}

如果我查看浏览器控制台,我可以看到:

Uncaught Sys.WebForms.PageRequestManagerParserErrorException: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed.

代码中似乎没有抛出异常,请求的文件被转换为正确的完整路径;我尝试了很多不同的东西——手动清除 headers,在结束前刷新,给出更明确的 content-type header,使用 AddHeader 而不是 AppendHeader,使用 TransmitFile 而不是 WriteFile ,还有更多。

有什么想法吗?

以防其他人遇到这种情况,问题是我在 ScriptManager 中将其注册为回发控件,而不是异步回发控件。

哦哦!