【问题标题】:How can I tell if Response data has been sent to the client yet in ASP.NET?在 ASP.NET 中,如何判断响应数据是否已发送到客户端?
【发布时间】:2023-03-25 16:25:01
【问题描述】:

我正在 C#/ASP.NET 中编写一个辅助方法,将文件流式传输到浏览器,我希望能够在清除响应标头/内容之前检测是否有任何内容已写入浏览器并发送文件字节。如果调用我的辅助方法的页面设置不正确,那么在我尝试清除之前,“正常”页面标题和内容似乎有可能(甚至可能?)整个响应并从文件数据重新开始。那么,有什么方法可以判断数据是否已经发送?

基本上,我在这个例子中寻找类似假属性 BytesSent 的东西:

if (response.BytesSent == 0)
{
    response.ClearHeaders();
    response.ClearContent();
    response.Clear();

    response.ContentType = "application/octet-stream";
    response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
    response.AppendHeader("Content-Length", new FileInfo(path).Length.ToString());

    //
    // etc. (stream the file)
    //
}
else
{
    // throw an exception (or handle the problem in some other way)
}

【问题讨论】:

    标签: asp.net streaming response httpresponse


    【解决方案1】:

    我不知道您要寻找的财产是否存在,但一般来说,您不会这样做。基本上,如果您的意思是 System.Web.UI.Page 的实例(通常是 .aspx 文件),则这种调用不是您希望从“页面”进行的调用。相反,请使用处理程序 (.ashx) 进行此类工作。处理程序是System.Web.IHttpHandler 的实现,您应该从ProcessRequest() 方法中调用此方法(或者只是将您的逻辑放在ProcessRequest() 中)。

    【讨论】:

      猜你喜欢
      • 2014-05-12
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      • 2017-08-11
      • 1970-01-01
      • 2012-06-15
      • 2011-06-06
      • 1970-01-01
      相关资源
      最近更新 更多