PDF saved as aspx/ashx over HTTPS - asp.net

I have an ashx handler that displays on browser a PDF from binary data, I'm using .NET Framework 4.0, IIS 6 and Chrome browser:
Dim s As System.IO.MemoryStream = HttpContext.Current.Session("tmp_binaryData")
s.Seek(0, System.IO.SeekOrigin.Begin)
With HttpContext.Current.Response
.ClearContent()
.ClearHeaders()
.ContentType = "application/pdf"
.AddHeader("Content-Disposition", "inline; filename='test.pdf'")
.BinaryWrite(s.ToArray)
.Flush()
End With
When accessed from HTTPS and the user tries to save the file (clicking on the save button from the PDF viewer's toolbar) the file's saved as ashx and not pdf. This doesn't occur if the web application is accessed from HTTP (port 80).
Is worth to mention that if I change the ContentType to "attachment/pdf" the file is automatically saved as PDF correctly.
I've used all sort of header combinations with no success, disabled Chrome's PDF Viewer, tried Adobe Reader, checked the file compresion option on IIS, verified MIME types, just to list some.
As an additional information, I'm using this same tecnique on another webapplication hosted on IIS7 on another server and the problem is not present, so it has something to be with the IIS 6 configuration.
UPDATE Jan/05/2017
I have loaded a test pdf from file via Response.Redirect("test.pdf") on production server and the file saves successfully on Chrome. So, I compared the headers of both display methods:
Response.Redirect() method:
headers="
Accept-Ranges: bytes
Content-Length: 696505
Content-Type: application/pdf
Date: Thu, 05 Jan 2017 18:05:09 GMT
ETag: "33dad7f8baccd11:11a1"
Last-Modified: Wed, 22 Jun 2016 19:19:18 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET"
ASHX handler (filestram) method:
headers="
Cache-Control: private
Content-Disposition: inline; filename='Prueba.pdf'
Content-Type: application/pdf
Date: Thu, 05 Jan 2017 18:09:58 GMT
Server: Microsoft-IIS/6.0
Transfer-Encoding: chunked
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET"
I noticed that the ASHX method is missing the "Accept-Ranges" and "Content-Lenght" headers, but it caught my attention that it has the "Transfer-Encoding: chunked" header. Do you think this could be causing the issue? I'll try to replicate the first method headers on the ASHX.

Well, I had to generate the PDF file physically on the server and then send it to the client's browser with Response.Redirect():
Dim s As System.IO.MemoryStream = HttpContext.Current.Session("tmp_binaryData")
Dim serverPath As String = "~/temp/"
System.IO.File.WriteAllBytes(HttpContext.Current.Server.MapPath(serverPath + HttpContext.Current.Session("tmp_fileName")), s.ToArray())
HttpContext.Current.Response.Redirect((serverPath + HttpContext.Current.Session("tmp_fileName")))
Those generated files need to be deleted when the session ends or expires, which can be done in Global.asax .
Another workarround would be using the original method (write bytes to browser) and instead of clicking on the save icon the user would click on the print button and then save the PDF file.

Related

Export CSV using Classic ASP

I have a classic ASP application with a page that will export a CSV file. It works in all browsers except Internet Explorer (IE). It worked in IE before the company updated everyone's computer to Windows 8 and IE10. I've tried compatibility mode on and off and I have used F12 to change the Browser Mode and Document Mode. I have the following code to set headers and etc...
Response.ContentType = "application/csv"
Response.AddHeader "Cache-Control", "no-cache"
Response.AddHeader "Content-Disposition", "attachment; filename=myfilename.csv"
I've also tried Response.Content-Type="text/csv" with no success. I've been banging Google hard for a day or two looking for resolutions but cannot find any help. Does anyone have some suggestions?
EDIT: Below is some more information I've pulled from Fiddler about the headers. Also, I should have mentioned that Fiddler shows the data is being written to the Response.
HTTP/1.1 200 OK
Cache-Control: no-store, no-cache,private
Content-Type: text/csv
Server: Microsoft-IIS/7.5
Content-Disposition: attachment; filename=somefilename.csv
Persistent-Auth: true
X-Powered-By: ASP.NET
Date: Thu, 14 Aug 2014 17:41:56 GMT
Connection: close
UPDATE:
I've been able to determine the issue is occurring due to the fact I am uploading a file and then trying to export file in the same Request/Response cycle. When I submit the data manually (via hidden fields) and not upload the file, the download works. So now I am trying to figure out a fix for this situation.
RESOLVED
It turns out to be an Internet Explore plus Windows Update issue. See the link below for more information.
Problem Description

How to solve "Chunked body did not terminate properly with 0-sized chunk."?

I have an RSS feed. When I browse to the feed with Fiddler Web Debugger open, Fiddler throws this error at me:
Chunked body did not terminate properly with 0-sized chunk.
The response from the server that triggered the error looks like this:
HTTP/1.1 200 OK
Date: Tue, 22 Jan 2013 21:00:49 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Cache-Control: private
Content-Type: text/xml; charset=utf-8
Content-Length: 30985
<rss version="2.0">
<channel>
... etc
The owner of the RSS is reporting problems when trying to submit the site to RSS aggregators.
I tried to validate the rss here: http://validator.w3.org/appc/. The response was this:
IncompleteRead(30985 bytes read) (IncompleteRead; misconfigured server?)
However, if I browse to the rss and copy past the code into this validator: http://validator.w3.org/appc/#validate_by_input, then everything validates correctly.
How do I correct this? This is a C# ASP.NET webforms project running on .NET 3.5 in IIS6.
Update
It appears that I was using Fiddler incorrectly. After unchcking the Decode option, here is the server response:
HTTP/1.1 200 OK
Date: Tue, 22 Jan 2013 21:22:03 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Transfer-Encoding: chunked
Cache-Control: private
Content-Type: text/xml; charset=utf-8
7909
<rss version="2.0">
<channel>
... etc
The data you posted above is not what the server sent. The response from the server contained a HTTP Header Transfer-Encoding: chunked but your data was not properly in the HTTP-chunked encoding format.
Please update your question with the actual data, as captured by Fiddler, making sure the Decode option in Fiddler's toolbar is NOT checked.
(As to the root cause of the problem, did you mistakenly call Response.Close()? See this article for an explanation of why that's the incorrect way to complete a HTTP response.)

IE8: Unable to download file sent through Silverlight and ASP.NET

In our ASP.NET web site we have developed an aspx page that allows the user to download a file. The file path is sent as a parameter and then the file contents are read and written to the response stream. The code that we have used is the following:
string filepath = HttpContext.Current.Request.Params["FilePath"];
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filepath));
Response.TransmitFile(filepath);
Response.Flush();
Everything works as expected in our development environment, but when we use this piece of code in our production server, we noticed that when trying to download almost all kind of files, nothing happens in the browser. It just opens a new window for that aspx page, but then it gets closed almost inmediately. It is very weird since we have tried downloading .pdf, .doc, .xls, .txt and image files with no luck, except with some (not all) .msg files.
We have being looking for a clue sniffing the HTTP traffic that reach to the browser with Fiddler, but we have seen nothing strange. In all cases the file contents are sent to the browser with no differences, so it seems that it is the browser doesn´t show the open/save/cancel dialog.
Here is a sample of the headers received in the browser with a failing file:
HTTP/1.1 200 OK Proxy-Connection:
Keep-Alive Connection: Keep-Alive
Content-Length: 421395 Via: 1.1
IBISA01 Date: Wed, 26 Jan 2011
12:02:54 GMT Content-Type:
application/octet-stream Server:
Microsoft-IIS/7.5 Cache-Control:
private Content-Disposition:
attachment;filename=P08-0656 Interflex
Especificación Inteface SGA ERP
Version 0.1.pdf X-AspNet-Version:
4.0.30319 X-Powered-By: ASP.NET
And these are the headers of a file that can be downloaded:
HTTP/1.1 200 OK Proxy-Connection:
Keep-Alive Connection: Keep-Alive
Content-Length: 290816 Via: 1.1
IBISA01 Date: Wed, 26 Jan 2011
12:03:29 GMT Content-Type:
application/octet-stream Server:
Microsoft-IIS/7.5 Cache-Control:
private Content-Disposition:
attachment;filename=Acalaracion final
Fichero ascii proveedores
Interflex.msg X-AspNet-Version:
4.0.30319 X-Powered-By: ASP.NET
In all cases, the full contents of the file appear after the headers with apparently no problems related to encoding.
We are wondering if there is some possibility to debug or trace the Internet Explorer activity to see why is rejecting to download the files.
The web server has Windows Server 2008 R2 and IIS 7.5. The browsers that we are using are IE 8.0 over Windows 7.
Many thanks in advance.
Jose Antonio Arroba
We had a similar issue with pdfs, try adding this.
Response.CacheControl = "no-cache";
Response.AddHeader("Pragma", "no-cache");
Edit Actually it's to do with your filenames:
How to encode UTF8 filename for HTTP headers? (Python, Django)
Try removing the ó from the example that doesn't work
Finally we were able to see what was happening with this odd behavior in Internet Explorer when trying to download files. I forgot to mention that we were trying to download the file from a Silverlight app that calls an aspx page in charge of writing the file contents in its response. It seems that the security engine of Internet Explorer treats this behavior as an automatic download, and blocks it by default when browsing from a non intranet server.
Enabling the "Automatic prompting for file downloads" setting in the Internet Explorer Security settings for the Internet zone solved the problem. What still puzzles us is why before enabling this setting we were able to download some of the files.
Thank you very much to all who has tried to help us. Hope that this answer could save time to those who could experience this same bevavior in the future.
Best regards,
Jose Antonio Arroba
Try this for each case...
Dim strExtension as String = ""
Dim strType as String = ""
strExtension = Path.GetExtension(filepath)
Select Case strExtension.ToUpper()
Case ".PDF"
strType = "text/pdf"
Exit Select
CASE ".DOC"
strType = "text/doc"
Exit Select
End Select
Response.Clear()
Response.ClearHeaders()
Response.Buffer = True
Response.ContentType = strType

Exporting rendered HTML page to Word is not working in IE

I have a rendered HTML page that I am exporting to MS Word and downloading on a button click.
Here is the code snippet in the button click.
` Me.EnableViewState = False
Response.ContentType = "application/vnd.ms-word"
Response.AddHeader("Content-Disposition", "attachments;filename=XXXXXXX.doc")
Response.Buffer = True
Response.BufferOutput = True`
The functionality works perfectly well in Firefox & IE when I checked in system testing environment (locally). However when it was moved on to the hosting server (production environment) the functionality is not working in IE but is still working perfectly in Firefox.
I am not sure on where to check for the exact issue. Could it be a caching related problem?
In IE it is just not opening the download window which we will obtain when the rendered HTML content type is changed and the response stream is flushed. No exception is thrown.
I received the following response header:
HTTP/1.0 200 OK
Cache-Control: private
Content-Length: 15189
Content-Type: application/vnd.ms-word;
charset=utf-8 Server: Microsoft-IIS/7.5 X-AspNet-Version: 2.0.50727
Content-Disposition: attachments;filename=NewAccountForm.doc X-Powered-By: ASP.NET
Date: Fri, 18 Mar 2011 10:18:07 GMT X-Cache: MISS from Gateway X-Cache-Lookup: MISS from Gateway:808 Via: 1.0 Gateway (squid/3.0.STABLE10) Proxy-Connection: keep-alive
Is your hosted environment adding http headers? IIS could easily be configured to add headers that are messing up what you want to send out. It's actually quite common, and could be the issue. You'll need to determine this for sure, so here's a suggestion for investigating:
Try using a WebClient class and look at the Response headers.
Edit - updated
I just noticed - did you remember to put
Response.Clear();
before adding headers? It may not be the hosting environment at all. However, given that it works locally and not at your hosting environment, and assming that it is the same code, it still looks to me like something is different about the hosted environment, and the most logical option would be the headers.
I set Response.Charset = "" and always do Response.Flush(), Response.End(), and Response.Close() after I export the HTML.

Flex: Download file & close new window/tab in IE

I'm getting an anoying problem in IE6.02 when trying to download a file through flex + struts action, the browser opens a new window and doesn't close it after the download has finished.
The flex code is:
navigateToURL(url,"_blank");
The content headers are:
HTTP/1.x 200 OK
Date: Thu, 29 Oct 2009 22:00:44 GMT
Transfer-Encoding: chunked
Content-Type: application-download; charset=UTF-8
Content-Disposition: attachment; filename=myfile.pdf
X-Powered-By: Servlet/2.4 JSP/2.0
also, we tried with
Content-Type: application/pdf; charset=UTF-8
How do I close the new opened window automatically? In FF works perfectly.
Thanks in advance,
Calling navigateToURL with _blank opens a new window (unless the browser's popup blocker blocks it) but doesn't return a reference to the newly opened window. So we cannot close it programmatically. Closing such automatically opened download windows once the download is complete is up to the browser. Have you considered using the Flash's inbuilt FileReference class to download files? It wouldn't open a new window - all it does is to prompt user to choose a place to save the file. Check the link for an example.

Resources