I have code like this:
context.HttpContext.Response.Clear();
context.HttpContext.Response.Write(htmlString);
context.HttpContext.Response.End();
But when pages are loaded I have an unclosed HTML tag in them. When I replace Response.End() with Response.Flush() it works fine.
What is difference between Response.End() and Response.Flush()?
Response.Flush
Forces all currently buffered output to be sent to the client. The
Flush method can be called multiple times during request processing.
Response.End
Sends all currently buffered output to the client, stops execution of
the page, and raises the EndRequest event.
You should try using this code if you are not doing any processing on the page after Response.Write and want to stop processing the page.
context.HttpContext.Response.Clear();
context.HttpContext.Response.Write(htmlString);
context.HttpContext.Response.Flush(); // send all buffered output to client
context.HttpContext.Response.End(); // response.end would work fine now.
Related
I need to render a xml document in either an new asp.net page or a pop up page.
I am following the article
I am getting the following error "Thread was being aborted." but the xml document is rendered in the page.
is there any better example
Try
If Not String.IsNullOrEmpty(tempFilePath) Then
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/xml"
'Response.WriteFile(Server.MapPath(tempFilePath)) ' Todo Change path to temp location and add th
Response.WriteFile("c:\Test.xml")
Response.Flush()
Response.[End]()
End If
Catch ex As Exception
'TODO
Throw ex
End Try
Response.End explicitly throws that exception as result of aborting the current thread (Is Response.End() considered harmful?) - so if you are logging all exceptions or just watching in debugger you'll see ThreadAbortException.
To stop sending extra content you can follow recommendation in linked question (C#):
Response.Flush();
Response.SuppressContent = True
HttpContext.Current.ApplicationInstance.CompleteRequest()
Based on your comment you are trying to render XML as part of the same response as main HTML of the page and it is not really possible (at least end result will not be "downloadable file"). It is generally easier to serve files from separate handler that does not have any HTML rendering associated.
Requirement:
I want to download a file (*.docx) on the click of a button, first I read the bytes of the file, then I write the bytes to the response, this works fine and I have used this code several times before, but I am getting this weird behavior where the code executes successfully, without exceptions, but there is no response being sent back to the client (nothing happens, no response, no file download), furthermore, if I put the code in Page_Load event, the code works flawlessly, it only does not work in the button click event(i.e. on postbacks), here is the code that I am using:
Dim arrBytes() = File.ReadAllBytes(strFilePath)
Response.ClearHeaders()
Response.ContentType = "application/octet-stream"
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=test.docx")
Response.AddHeader("Content-Length", arrBytes.Length.ToString())
Response.BinaryWrite(arrBytes)
Response.Flush()
Response.SuppressContent = True
HttpContext.Current.ApplicationInstance.CompleteRequest()
Any help is much appreciated.
EDIT:
I tried 'Response.WriteFile instead ofResponse.BinaryWrite and Response.End instead of ApplicationInstance.CompleteRequest but nothing succeeded.
Turns out there was an UpdatePanel in the MasterPage, the problem was solved when I registered the button as a post back control ... That hurts I know.
So I solved it by using this line of code in the Page_Load event:
ScriptManager.GetCurrent(Me).RegisterPostBackControl(btnSubmit)
I'm having difficulty sending an XML stream to the client browser. I've researched this considerably and everything looks right - moreover, similar code works in a previous version of this app. Any ideas what I could be doing wrong?
The following code throws no errors, but does not download a file on the client machine.
Public Shared Sub Export(ByVal source As DataTable)
Try
With Current.Response
Dim xml As String = CreateExcelXMLFromDataTable(source.DefaultView)
.Clear()
.Buffer = True
.ContentType = "application/vnd.ms-excel"
.AddHeader("Content-Disposition", String.Concat("attachment;filename=", "export.xlsx", ";"))
.AddHeader("Content-Length", xml.Length.ToString)
.Charset = ""
.Write(xml)
.Flush()
.Close()
End With
Catch ex As Exception
Console.WriteLine(ex.Message.ToString)
End Try
End Sub
Thanks!
If you are calling this function in an Ajax request it will not work. You have to cause a full postback to send the file to the client.
You can send the file without causing a full postback in the current page using an popup window (window.open) or an iframe with the URL of the download asp.net page, which will call the Export function.
I have an ASP web forms page with a button. On postback the button sends some XML content back to the user as a file. It has been working however in one case with a string with a length of 16759 the downloaded file has been cut short by 10 bytes. Both Chrome and Firefox have exhibited the same behaviour.
The solution has been to change the content-type from "text/xml" (I also tried "text/plain") to "application/octet-stream". However I would like to understand why the other content-types behave in this way.
My code is as follows. (I've played around with a few different methods and they did not change anything)
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "text/plain";
HttpContext.Current.Response.AddHeader("Content-Length", content.Length.ToString());
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"test.txt\"");
HttpContext.Current.Response.Write(content);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
All you have to do is not call Close on the Stream. Don't ask me for an explanation, all I know is it works.
Explanation per the MSDN link for HttpResponse.Close kindly provided by Ray Cheng:
This method terminates the connection to the client in an abrupt manner and is not intended for normal HTTP request processing. The method sends a reset packet to the client, which can cause response data that is buffered on the server, the client, or somewhere in between to be dropped.
In an application we have here we create an advice booklet pdf's for users on a web app. These are quite hefty documents and take upto 30 seconds to generate. We decided the best method for this was to generate the pdf in the background of the application before the user requests it.
If the user requests the PDF a page is opened that checks if the booklet is complete and when it is displays it to the user.
This works great in every case unless adobe has been set to NOT 'Display PDF in browser' and the user is using IE8 or IE7.
In this case we get a warning message about a download file and the file is displayed as Binary text.
We pull the pdf when the application triggers an ajax call that generates that pushes the content using the following code.
To loop until the booklet is ready.
If pdfState = PdfBooklet.Status.Complete Then
If Me.SupportsScript Then
' Send signal back to Ajax call saying we're ready
Response.ClearContent()
Response.Write("complete")
Response.End()
Else
' Non-JS can just have it delivered straight away
pdf = CType(HttpContext.Current.Session(PdfBooklet.sSessionBookletKey), Byte())
ServerPDFBooklet(pdf)
End If
Else
' Not finished yet
Response.ClearContent()
If Me.SupportsScript Then
If isAjaxRequest Then
' Signal back to Ajax to wait a bit long
Response.Write("waiting")
Response.End()
End If
Else
' Non-JS => page refresh
Response.AddHeader("refresh", "3")
End If
End If
And to write the pdf
With Response
.Clear()
.ClearHeaders()
.AddHeader("Content-Disposition", "inline; filename=" & pdfFilename & ".pdf")
.ContentType = "application/pdf"
Try
.BinaryWrite(binaryPDF)
.Flush()
.End()
Catch Ex As HttpException When Ex.ErrorCode = &H80072746
'Client disconnected
End Try
End With
The easy way for us to fix this is to just response.redirect to a new page to serve the booklet when its complete but we would rather not do this.
Any ideas...?