我有一个带有 IHttpHandler 的 ashx 文件。当我向这个 IHttpHandler 发布一些数据时,我会做一些工作,创建一个文件,然后希望将该文件返回给用户,以便他们可以通过浏览器保存文件。
创建文件后,这就是我尝试将文件写回响应的方式:
HttpResponse response = context.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", "attachment; filename=MYFILE.EXT");
response.WriteFile("C:\tempstuff\MYFILE.EXT");
在稍后的 finally 块中,我将调用:
response.End()
当我调用这个处理程序时,什么也没有发生。返回响应 200,不抛出任何错误 - 但浏览器不会提示用户保存此文件。
Fiddler 捕获的响应如下所示:
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Thu, 23 Aug 2012 12:12:19 GMT
X-AspNet-Version: 4.0.30319
Content-Disposition: attachment; filename=MYFILE.EXT
Cache-Control: private
Content-Type: application/octet-stream
Content-Length: 781053
Connection: Close
[raw content of the file here]
这个回答对我来说是正确的。它包含文件的内容 - 但是在任何主要浏览器下,都没有文件对话框提示我保存文件。
我在这里做错了什么?
更新:如果有帮助,这里是我使用 Web 应用程序中的 JavaScript 调用此 HttpHandler 的地方。
$.ajax({
type: 'POST',
url: ashxUrl,
data: postData,
success: function (result) {
// Doin' stuff on success
},
error: function (error) {
// Doin' stuff on error.
}
});