开发者

How can I tell if Response data has been sent to the client yet in ASP.NET?

I'm writing a helper method in C#/ASP.NET that streams a file to the browser, and I would like to be able to detect if any content has been written to the browser prior to clearing the response headers/content and sending file bytes. If a page that makes a call to my helper met开发者_如何学编程hod is not set up correctly, it seems like it would be possible (likely even?) for "normal" page headers and content to get sent to the browser prior to my attempting to clear the whole response and start fresh with file data. So, is there any way to tell if data has already been sent?

Basically, I'm looking for something like the fake property BytesSent in this example:

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)
}


I don't know whether the property you seek exists, but generally, this is not how you would go about this. Basically, this sort of call is not one you want to be making from a "Page," if by that you mean an instance of System.Web.UI.Page (which .aspx files typically are). Instead, use a handler (.ashx) for this kind of work. The handler is an implementation of System.Web.IHttpHandler, and you should call this method from within the ProcessRequest() method (or just put your logic within ProcessRequest()).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜