c# - 使用 Page.Response 向用户发送文件后,页面没有响应

标签 c# asp.net postback response

我创建了一个页面,允许用户在单击按钮时下载文件...按钮的 onclick 事件链接到以下代码块:

this.Page.Response.Clear();
this.Page.Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Zip;
this.Page.Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + System.IO.Path.GetFileName(filename) + "\"");
this.Page.Response.TransmitFile(filename);
this.Page.Response.Flush();
this.Page.Response.End();

下载工作正常,但现在当我尝试与页面交互时(例如,再次点击下载按钮),没有任何回传。

我是否错误地响应了下载请求(我应该使用不同的/新的响应对象),还是我需要做其他事情才能在下载后激活页面?


编辑:

所以我尝试结合两个海报的建议来创建 httphandler,并从按钮的点击事件调用 Response.Redirect 到处理程序。

    void submitButton_Click(object sender, EventArgs e)
    {
        label.Text = "Boo!";
        this.Page.Response.Redirect("~/ViewAttachment.ashx?id=foo", false);
    }

如果我在调试器上逐步执行此操作,它会在重定向调用后继续,但页面只会返回到按钮不起作用的状态,并且标签具有默认值。我现在做的重定向有误吗?

最佳答案

如果使用另一个处理程序一个选项?

这是我之前使用过的精简版(欢迎提出建议,这是一篇快速撰写的文章)。 The HttpHandler (AttachmentFile 只是一个包含 blob 数据和上传文件时收集的一些属性的类):

public class AttachmentHandler : IHttpHandler
{
  public const string QueryKeyID = "ID";

  public void ProcessRequest(HttpContext context)
  {    
    var r = context.Response;
    var attachmentID = context.Request.QueryString[QueryKeyID];

    Attachment a = DataContext.GetById<AttachmentFile>(attachmentID);

    r.ContentType = a.ContentType;
    r.AppendHeader("Content-Type", a.ContentType);
    r.AppendHeader("content-disposition", string.Format("attachment; filename=\"{0}{1}\"", a.AttachmentName, GetExtension(a.FileName)));
    r.BufferOutput = false; //Stream the content to the client, no need to cache entire streams in memory...
    r.BinaryWrite(a.BlobData);
    r.End();
  }

  private static string GetExtension(string fileName)
  {
    if(fileName.IsNullOrEmpty()) return string.Empty;
    var i = fileName.LastIndexOf(".");
    return i > 0 ? fileName.Substring(i) : string.Empty;
  }
}

web.config 中:

<system.web>
  <httpHandlers>
    <add verb="*" path="ViewAttachment.ashx" type="MyNamespace.AttachmentHandler, MyWebDllName"/>
  </httpHandlers>
</system.web>

然后你所要做的就是在页面上以 ~/ViewAttachment.ashx?ID=5 的形式呈现一个链接,点击按钮将下载文件,但不会打乱你页面的生命周期完全没有。

现在有更多的考虑因素,比如安全性等等……我在这个例子中删掉了它们。我还使用这种链接样式:~/Attachment/{id} 通过 webforms 路由...如果您对这些中的任何一个感兴趣,我将更新以包含它们。或者您可能会完全讨厌这种方法……只是让您知道这是一种选择。

关于c# - 使用 Page.Response 向用户发送文件后,页面没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2188622/

相关文章:

c# - 如何使 csc.exe C# 6 感知

c# - 如何编写 LINQ 查询以仅基于特定属性检索不同的记录?

c# - 在 URL 路由 4.0 中找不到资源

asp.net - 用于多种语言的 ASP.NET 路由的正则表达式

c# - 如何检测pictureBox是否成功显示图片?

asp.net - "return View()"和 "return PatialView()"的任何区别仍在 MVC 3 中

.net - 在更新面板中提交表单后运行 javascript?

c# - 单击按钮时使用 JS 更改 asp :HiddenField. 值

javascript - 如果 ASP.NET 中的 href 为空,则禁用 anchor 标记

c# - 如何从数据库绑定(bind) GridView