无法打开下载保存对话框

使用下面的代码我无法显示打开/另存为文件对话框:

public void ProcessRequest(HttpContext context) { string link = context.Request.QueryString["Link"]; string extension = Path.GetExtension(link); string fileName = Path.GetFileName(link); string fullPath = String.Format("{0}\\{1}", context.Server.MapPath("~/Content/Uploads/"), fileName); if (File.Exists(fullPath)) { context.Response.ClearContent(); context.Response.ClearHeaders(); context.Response.AddHeader( "Content-Length", new FileInfo(fullPath).Length.ToString()); string contentType; switch (extension) { default: contentType = "application/octet-stream"; break; } context.Response.ContentType = contentType; context.Response.AddHeader( "Content-Disposition", String.Format("attachment; filename={0}", fileName)); context.Response.WriteFile(fullPath, true); context.Response.Flush(); } } 

我试图关闭响应,保持响应打开,使用TrasmitFile() ,但我从来没有得到任何对话或任何反馈。 我也试过调试它,但没有抛出exception。 在IE 7/8和Chrome中尝试过。 任何帮助表示赞赏。

谢谢!

以下是Fiddler输出:

HTTP / 1.1 200 OK Cache-Control:private Content-Length:3813 Content-Type:application / octet-stream服务器:Microsoft-IIS / 7.5 Content-Disposition:attachment; filename = b1af9b34-28cc-4479-a056-8c55b41a5ece.txt X-AspNet-Version:4.0.30319 X-Powered-By:ASP.NET Date:Thu,23 Dec 2010 21:51:58 GMT

 * Home * Hotels * Reviews * Community * Travel Guide * Travel Insurance * Contact us 

* FIDDLER:RawDisplay被截断为128个字符。 右键单击以禁用截断。 *

终于想通了。 我发布的代码实际上没有问题。 正如您在Fiddler输出中看到的那样,文本文件的内容已成功写入响应流,并且使用的标头也是正确的。 实际问题来自实际的http请求是如何产生的。 我用了一个

$获得(urlToGenericHandler);

请求使用jQuery。 特别是我无法使用AJAX或回调模型下载文件的原因超出了本答案的范围。 请在此处查看支持的jQuery数据类型

无论如何,我将使用AJAX的调用更改为使用基本的回发。

感谢所有帮助。

尝试改变

 contentType = "application/octet-stream"; 

 contentType = "application/download"; 

更新 :尝试交换标题和内容类型的位置

 context.Response.AddHeader( "Content-Disposition", String.Format("attachment; filename={0}", fileName)); context.Response.ContentType = contentType; context.Response.AddHeader( "Content-Length", new FileInfo(fullPath).Length.ToString());