Different ways of ending a context response - asp.net

I was working with a generic handler that sends back an XML file as the response, and using code that I already had that did the same thing, from 2 different sources.
The thing is, both sources end their block of code differently, first I have this block
context.Response.Clear()
context.Response.AppendHeader("Content-Disposition", "Attachment; filename=filename")
context.Response.ContentType = "text/xml"
context.Response.Write(myXML)
context.Response.Flush()
context.Response.End()
And then I have the same thing, except that the last line is context.ApplicationInstance.CompleteRequest() instead of context.Response.End()
So I wanted to know what was the difference between both of those lines and which one should I be using
Thanks.

Related

Unreadable excel content Epplus

I am making a Post request and receiving the response from an end point, through which i receive the excel content.
I have used this end point before and tried binding a email worker, which works fine. (Conforming end point response is clear).
Now with a different requirement, i need to make the post call to this end point and download the excel file.xlsx file hence generated is corrupted and i excel tries to recover it once the file is downloaded.
Have gone thorugh different threads and tried almost everything.
Nothing seems to work.
try 1:
Response.Clear();
stream.Flush();
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName.Replace("\"", String.Empty));
And while debugging i have made sure to close the response. (Response.End()).
Have even added the explicit headers
Response.AddHeader("content-disposition", "attachment; filename=\"" fileName".xlsx\"");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Try 2
have explicity written the memoryStream to the response.
Response.BinaryWrite(tgtBytes);
Have ensured Response.Clear before writing to response and making sure of memoryStream.dispose and Response.End.
Have even used. Response.ClearHeaders().
Try - 3.
Instead of MemoryStream, tried with filestream, saving in a file and downloading from the File written. Problem still Persists.
I am getting a binaryStream as response and no encoding in done as it isn't hex value.
Either the stream is corrupted ( which is likely not the case, as i use the end point for different requirements) or the response is corrupted.
how should i check what is the exact cause ??
Please Let me know what else can i try.

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.

Exception While Downloading PDF file in asp.net

I am downloading a file in asp.net
Here is the code
Response.ContentType = "Application/.pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename="+extractFileName+".pdf");
Response.TransmitFile(extractFilePath);
Response.Flush();
Response.End();
The file is downloading properly but at Response.End(); it throws following exception:
{Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}
The provided message is not an exception, but a message indicating that it cannot show you the error due to optimizations performed by the compiler, and due to the current code location.
Try removing the response.End and see if it will allow you to see the error.
There are several issues.
I think the main issue will be that you're using extractFileName for both the name that will be used to open/save the file at the browser, and also as the physical name of the file to transmit. So you are either using a full path for the content-disposition when it needs just a filename... or you are not giving a full path for the transmit.
You are also using an incorrect MIME Type for the PDF, which should be application/pdf
(And you are also include .pdf at the end of the extractFileName, so I presume the variable doesn't already include the extension?)
If extractFileName is the full physical path to the file (including extension), then try replacing...
Response.AppendHeader("Content-Disposition", "attachment; filename="+extractFileName+".pdf");
with...
string contentFileName = System.IO.Path.GetFileName(extractFileName);
Response.AppendHeader("Content-Disposition", "attachment; filename="+contentFileName);
TransmitFile() cannot be used for files outside the directory structure of your website. In that case use another way to write the file to the Response.
Remark:
If the filename contains multiple points (.) or characters like comma (,), some browsers will mess up the filename. Add extra quotes to the filename to avoid problems.
Response.AppendHeader("content-disposition", "attachment; filename=\"" + file + "\";");

ASP.NET Export - Response not ending?

I'm trying to export some text to a text file, and that part works fine. The trouble is that the text files get a bunch of HTML/.NET output at the bottom of them... In other words, it's like the response isn't ending and the page is trying to write the rest of the page. Here's the code:
Private Sub WriteData(ByRef Context As System.Web.HttpContext, Data As List(of String), fileName as String)
With Context.Response
.Clear()
.ClearHeaders()
.ClearContent()
.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName))
.ContentType = contentType
End With
For Each curValue in Data
Context.Response.Write(curValue)
Context.Response.Write(Environment.NewLine)
Next
Context.ApplicationInstance.CompleteRequest()
Context.Response.End()
End Sub
To call this, I just pass the HttpContext.Current and a list of data.
Does anybody know why this might happen? I'm not sure how to interpret it, and I've looked all over without much luck. My assumption was that the response wasn't actually ending with "Response.End()"...
Thanks,
Mike
My assumption is that you're using an .aspx to do this.
This would be a perfect scenario for a Generic Handler. Try using .ashx instead.
Here is a pretty simple tutorial if you need more info:
http://www.brainbell.com/tutorials/ASP/Generic_Handlers_%28ASHX_Files%29.html

Resources