No response in postback after writing binary to the response - asp.net

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)

Related

Response Redirect not working after sending email

I have a code that works with EPPlus library to modify some data from a dt to an excel file that it attachs itself and sends an email, and also downloads that file to the client sending it.
However from the following onClick method, it doesnt do anything but the SendModFile(), i think the text and stuff needs a postback thats why its not changing, that i can take away, but i must disable the button for the process not to send more than one email and redirect to the main menu, how can i acomplish this.
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Label1.Visible = True
Button2.Enabled = False
Label1.Text = "Sending..."
SendModFile()
Label1.Text = "Sent"
Response.Redirect("~/Main.aspx")
End Sub
Edit:
This is the end of the SendModFile() that lets download the file after sending the email, is there a way to optimize this, i believe this part is the one messing up due to Response.End()
Response.Clear()
Response.Buffer = True
Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AppendHeader("content-disposition", "attachment; filename=ExcelFileName.xlsx")
Response.BinaryWrite(memStream2.ToArray())
Response.End()
When you call Response.End, that's the end of the response. You can't then do a redirect.
One workaround is to have the user download the file in a separate HTTP request by providing a link or button that downloads the file, so that you still main control over the page they're accessing.

PDF file sometime being displayed as garbage

I am having a user who is reporting that files are being displayed as raw data in his browser. He uses Internet Explorer.
The files are being served via a .ashx handler file and it has been working until.
This is the relevant part of my .ashx handler:
context.Response.Clear()
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name)
context.Response.AppendHeader("Content-Length", size.ToString)
context.Response.ContentType = "application/pdf"
context.Response.TransmitFile(fullname)
context.Response.Flush()
HttpContext.Current.ApplicationInstance.CompleteRequest()
Can anyone figure something out of this screenshot?
Update: this behaviour appears on Windows 10 when running either IE 11 or Edge and only the second time a file is being opened. It happens for both .pdf and .docx files.
This is the code I use to stream PDFs to a client. It works in IE 11. The main difference is that I am using BinaryWrite which based on your code, you may not want to do..
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf");
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName + ".pdf");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.End();
There might be a solution here
I'll like this as well just in case..
According to this thread, it could be as simple as replacing Response.Close with Response.End (or in your case.. adding)
I finally found the answer myself - it had to do with the HTTP header content-length which i mistakenly submitted with a value exactly 1byte too large.
This caused the strange behavior in only IE/Edge and only Windows 10 as described in the OP.
I had the same problem with an aspx page that transmits file to browser in Page_Load event handler.
My mistake was an absense of
Response.End();
method call. When I added this line the problem has gone.

Display Xml document in Browser vb.net

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.

Differences between Response.End() and Response.Flush()

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.

On forcing download: File Download dialog opens twice in IE6 SP1

My ASP.Net page is supposed to create a document and force its download (open a "File Download" dialog). It works fine on most browsers but for some reason, on IE6 SP1 (windows 2000) the "File Download" dialog opens twice.
Any ideas why?
My very simple code (C#):
protected void bnCreateDocument_Click(object sender, EventArgs e)
{
string documentText = GetDocumentText();
Response.Clear();
Response.Charset = "";
Response.ContentType = "application/msword";
string filename = "MyDoc.doc";
Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
Response.Write(documentText);
Response.End();
Response.Flush();
}
Your code looks fine but there are a couple of odd things about it that I thought I'd point out.
If you're just fetching a file from the filesystem into that string, why not use Response.WriteFile() directly?
Also, Response.End() automatically calls Flush() if buffering is on, so you shouldn't be calling Flush() at the end like that - at best, it should be before the call to End. End() also raises a ThreadAbortedException, so if you can avoid calling it altogether, that would be ideal. If you can use HttpApplication.CompleteRequest(), that's a better approach.
There are some very tricky and obscure bugs to deal with when shutting down the Response object. If after dealing with the Flush and End calls it's still happening, I would examine what's going on with Fiddler, and perhaps try moving this code into an .ashx handler to get it out of the page lifecycle.

Resources