IE8: Unable to download file sent through Silverlight and ASP.NET - 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

Related

PDF saved as aspx/ashx over HTTPS

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.

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

IE 10 - File download issues

I'm trying to download an excel file (generated dynamically using C#\ASP.NET) and I get the IE10 View Downloads dialog when I click "Open" it says "abc.xls couldn't be downloaded" error but after clicking "Retry" it opens the .xls file properly in the second try.
When I test this in Firefox or Chrome it works fine.
I think this may explain the strange behaviour:
"Content-Length and Transfer-Encoding Validation in the IE10 Download Manager"
It seems that IE9 beta had introduced content-length and transfer-encoding validation when downloading files, but found it was too problematic since many servers didn't send proper values for these downloads that are processed through code. Apparently they turned it back on in IE10 however and just hoped for the best.
I'd wager that accurate values being sent when the download is started should clear up this problem. Of course, it shouldn't have been a problem to begin with... ai yi yi.
[Edit]
Turns out this problem was related (for me at least) with using Response.Close() and/or Response.End() in code. This article explains why you shouldn't use these 2 methods, and why HttpApplication.CompleteRequest is the method of choice. Changing our Response.End() and Response.Close() instances to HttpApplication.CompleteRequest solved our IE10 download issues. Like magic. Apparently MSDN now discourages use of these 2 methods (despite years of MSDN code examples containing them), and now advocates use of HttpApplication.CompleteRequest instead.
We were always at war with Eurasia...
[/Edit]
I was getting a similar behavior -
After fighting this issue for about 12 hours what worked for me:
Changing response header from
Content-Type: application/application/vnd.ms-excel
To
Content-Type: application/octet-stream
Note that I had another an unmentioned symptom: I was setting
Content-Disposition: attachment; filename="Inventory_10-10-2013.xls"
Despite that setting IE used the file name from the URL (so it said "getInventory couldn't be downloaded" - and it saved the wrongly named file in the downloads folder!).
When I changed the 'Content-Type' IE started honoring the file name from the header.
For the record here are all the response headers that I'm setting:
HTTP/1.1 200 OK
Pragma: Public
Expires: Fri, 11 Oct 2013 16:33:38 GMT
Cache-Control: max-age=1
Content-Disposition: attachment; filename="Inventory_10-10-2013.xls"
Content-Transfer-Encoding: BINARY
Set-Cookie: fileDownload=true; path=/
Content-Type: application/octet-stream;charset=UTF-8
Content-Length: 7680
Date: Thu, 10 Oct 2013 16:33:38 GMT

What can cause IE9 to fail on a redirect?

I'm loooking at an existing web forms app that I didn't write. It's working as expected in IE8 and FF, but fails in IE9 with:
"Internet Explorer cannot display the webpage"
The code is a simple handler that's doing a context.Response.Redirect.
Using Fiddler, I can see the 302 response, so everything looks fine.
Any ideas why IE9 behaves differently, or what I can do to fix?
Edit due to request for code:
Sure, here's the line:
context.Response.Redirect("file:" & Filename.Replace("/", "\"))
Fiddler shows:
HTTP/1.1 302 Found
Date: Thu, 09 Aug 2012 19:01:24 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Location: file:J:\Replay\Meetings\Meetings-2012.pdf
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 254
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>
I'm asking just to make sure, but do you have J:\Replay\Meetings\Meetings-2012.pdf file locally on your disk? The file:// protocol is used only to access local files. I suppose it's ok, as you wrote it works as expected in other browsers.
If so, I've read that this kind of error can be caused by invalid url to the file.
Try to redirect like this:
context.Response.Redirect("file://" & Filename);
Let me know if this helps.
This may be a zone elevation issue. Specifically, IE tries to prevent sites in one security zone from elevating themselves to another security zone. Redirecting to your local machine from outside your local machine is considered dangerous.
Possible fixes (I am not sure if these will work in IE9):
1. Add the site that triggers these redirections to the Trusted zone.
2. Change your security settings. Notice the "Websites in less privileged web content zone can navigate into this zone" setting (Internet Options -> Internet Zone -> Custom Level). You need to set that to "Enable" or "Prompt" for the "My Computer Zone." I suspect this can be done by either adding the "My Computer Zone" to your zones list ( http://support.microsoft.com/kb/315933 ) or by editing the "My Computer Zone" directly (via the registry). You may also need to add the HKCU\Software\Microsoft\Internet
Explorer\Main\Disable_Local_Machine_Navigate key (set to 0 REG_DWORD).

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.

Resources