Skip to main content
 首页 » 编程设计

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

2024年02月24日19lidabo

我创建了一个页面,允许用户在单击按钮时下载文件...按钮的 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 路由...如果您对这些中的任何一个感兴趣,我将更新以包含它们。或者您可能会完全讨厌这种方法……只是让您知道这是一种选择。