IE not showing PDFs with caching disabled - asp.net

I've been asked to implement a security requirement that we instruct browsers not to cache sensitive data. This is all fine for the ASPX content using the standard instructions:
Response.Expires = -1;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
However when I set these headers for PDF downloads, IE8 won't show the PDF (haven't tried other IE versions yet, kinda moot, I need it working on all of them, even IEfreaking6). Seems to work in firefox 4 beta, but I haven't double checked that it's definitely not caching it. Here is the abridged version of the code I'm using to serve the PDFs:
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
//This stops the PDFs from being viewed :(
//Response.Expires = -1;
//Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Response.Cache.SetNoStore();
Response.ContentType = mime;
Response.AddHeader("Content-Disposition", disposition);
Response.BinaryWrite(file);
Response.End();
Where in the case of PDFs the mime type is set to:
private const string mimeTypePDF = "application/pdf";
The disposition is set to:
var disposition = String.Format("{0};filename=\"{1}\"", SendInline ? "inline" : "attachment", Path.GetFileName(filename));
I'm going to play-around a bit more, maybe forcing them to download as mimetype "application/octet-stream" might work, but that would stop the nice open PDF's in a new browser window from working.
Has anyone had any success with preventing IE from caching PDFs from the server side and successfully displaying them?
Just to give a clear example about what happens. In one scenario user's can select a bunch of reports from a list, these are compiled into a PDF and the PDF is shown in a new browser window. With the caching enabled the browser window opens, but remains resolutely blank.

I've had the same problem with IE a few years ago and let is cache since I didn't have a requirement to disallow it.
However, since users are free to save a PDF document once the browser shows it, how do you plan on prevent them from do that?
Not that this will solve your problem but when sending physical files you should Response.TransmitFile instead of BinaryWrite. It's much faster and more efficient in terms of memory utilization since you don't need to load the entire file in memory before sending it.

Looks like this issue has been resolved in IE9.
I can now successfully execute the following:
Response.Expires = -1
Response.Cache.SetNoStore()
Response.AppendHeader("Pragma", "no-cache")
Response.ContentType = "application/pdf"
Response.BinaryWrite(myByteBuffer)
Response.Flush()
Response.Close()
Enjoy!

I'm going to say it's not currently possible, nothing I tried seemed to get it to work. Try and get your customers to use firefox instead! :)

I also believe it's a bug in Internet Explorer. I was setting the cache-control header to no-cache and having the same problem. Also note that in Internet Options > Advanced > Security there's a 'Do not save encrypted pages to disk' option that could affect it.
Removal of the cache-control header from the response sorted out my issue. I also then tried checking the above mentioned option, and it seemed to work even better for me. Iinstead of storing the PDF in %LocalAppData%\Microsoft\Windows\Temporary Internet Files, it actually caused IE8 to issue a dialog allowing me to choose where to save it (which is actually what I wanted in my case).

This issue of showing pdf (and other document types) in-browser with the use of the no-cache header has been filed as a bug to Microsoft: http://support.microsoft.com/kb/316431. When you try to open a document in this case, IE tries to read it from cache, but it isn't there.
Unfortunately, the folks at M$ said this "works as designed" and users should not use the no-cache header... go figure.

Related

iTextSharp not working in IE x64

I just transitioned my ASP.NET MVC project from Spire.PDF to iTextSharp (due to the limitations in the free version of Spire.PDF). However I cannot get even the simplest example to work correctly for some reason.
What happens is that the browser (IE 11 x64 in this case) will just display an empty grey page. If I keep this page open for a while then Adobe Acrobat displays an error message (103:103).
The interesting part is that when I save the file (either by adding a Content-Disposition header or by using Fiddler) then the PDF opens without problems. I also found out that Edge and the 32 Bit version of IE will display the PDF file just fine.
Here is my sample Action method:
public ActionResult DownloadPdf() {
var document = new Document(PageSize.A4, 50, 50, 25, 25);
var output = new MemoryStream();
var write = PdfWriter.GetInstance(document, output);
var titleFont = FontFactory.GetFont("Arial", 18, Font.BOLD);
document.Open();
document.Add(new Paragraph("Test Receipt", titleFont));
document.Close();
Response.ContentType = "application/pdf";
Response.BinaryWrite(output.ToArray());
return new EmptyResult();
}
This is what the result looks like: https://onedrive.live.com/redir?resid=17E4A59AD907D9BA!259495&authkey=!ABsQUl-TiR668xI&ithint=folder%2cpng
Any ideas other than setting Content-Length or Response.Buffer? (I tried those already)
Update 1: I'd like to reply to some of the comments
#ChrisHaas even after changing the content type, IE would still display the grey page. However, I used Fiddler to save the response (once with header and once without) in the OneDrive link which you can find in my question above.
#Matt do you mean F12 dev tools? It won't load up correctly on the grey page, it's just a blank white area. So I can't really inspect anything.
#Paulo I tried this before and it didn't have any effect. However the Content-Length seems to be correct anyway according to Fiddler.
I still don't understand what exactly the problem is but I decided to test this on a different PC and determine whether it is a server-side or client-side problem.
I reconfigured IIS Express to allow remote connections and accessed the PDF file from another system (also Win 10 Pro x64 with IE 11) and it worked perfectly. It also behaved correctly depending on the content-type (i.e. download dialog for octet-stream and inline PDF viewer for application/pdf).
Next thing I did was reinstall Adobe Acrobat Reader DC on my dev machine but the problem was still there, even after rebooting and clearing the IE cache. So the last thing I tried was downgrading from version DC to X - this actually worked and will now display PDFs in the browser normally.
Like I said, I don't understand exactly what the problem was but at least I can continue working on my project now.
Thanks everyone for the suggestions though!

force user to download rather then open xlsx file in browser

We have some users who when they open an excel file on my website it takes ages. If they simpely Save as and then open it's quick.
They have the same issue on other sites so it's a problem on their side.
However is there a way to force the browser to only offer save and not offer open?
As noted here:
Is there a way to force the user to download a file from a href link rather than to open it in a browser window?
and here:
Forcing to download a file using PHP
I'm currently using:
Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", "attachment; filename=Report.xlsx");
Response.AddHeader("Content-Length", new System.IO.FileInfo(fileName).Length.ToString());
But this is still offering the open option.
Is there a way to force this or is it simply dependent on the users browser settings.
Just send a different Content-Type (application/octet-stream):
Response.ContentType = "application/octet-stream";
This way the browser doesn't recognize the format and just proposes to save the file.
--- EDIT ----
Today, I got to know another header field, that probably fixes your problem:
"X-Content-Type-Options: nosniff"
Description: "The only defined value, 'nosniff', prevents Internet Explorer from MIME-sniffing a response away from the declared content-type. This also applies to Google Chrome, when downloading extensions.[31]"
(http://en.wikipedia.org/wiki/List_of_HTTP_header_fields)
Although the Question is quite old I am going to answer...
For IE8/9 and Chrome this worked for me:
Response.AddHeader("X-Download-Options", "noopen");

Displaying images and documents using asp.net across several browsers

I have a webpage called DisplayBinaryData.aspx - the purpose of this page being to display/download any word, excel, pdf or images. I call this webpage and pass the id of my BinaryData entity using a querystring. The BinaryData entity contains the file, filename and contenttype uploaded using the asp.net fileUploadControl. The code in the page load is below:
BinaryData obj = GetBinaryObjectById(int.Parse(Request.QueryString["id"]));
Response.Clear();
Response.BufferOutput = true;
Response.AddHeader("Content-Disposition", "attachment; filename=" + obj.FileName);
Response.ContentType = obj.FileContentType;
Response.BinaryWrite(obj.BinaryFile);
Response.Flush();
Response.Close();
Response.End();
This code executes perfect in IE,but fails when executed in FireFox. IE prompts the user, either to save or open the content. FireFox also prompts the user, but the dialog box fails to save or open any content. When executing this in google chrome - there is no dialog box, it starts downloading the content automatically.
My question: I need this code to be compatable with FireFox - any suggestions?
The behavior you mention with Chrome is just do to the default settings for Chrome. You can change those by going to the "Under the hood" tab of the Options window. Then select the "Ask Where to save each file before downloading" checkbox.
Does your obj.FileName have a space in the name?
See this post on "Content Disposition" in different browsers.
Content Disposition in different
browsers
Today I had to resolve an issue where
in different browsers the filed
dynamically generated download worked
very differently / at all
The setup, we had an xml file with a
custom extension, say .mj, which was
being served up by ASP. The HTTP
Header had a content disposition
header and a response type set.
Response.AddHeader "Content-Disposition", "attachment; filename=""our file.mj"""
Response.ContentType = "text/xml"
This worked fine in Internet Explorer, the
file was downloaded as "our file.mj".
However FireFox and Chrome acted very
differently, in FireFox the file was
downloaded as just "our", and Chrome
as "our file.xml". In FireFox it
appears that the issue is caused by
having a space in the file name, this
forum post by funkdaddu helped me on
this, so by removing the space FireFox
could now download the file as
"ourfile.mj". ...

Problem with CSV download to IE 6

I have a friend experiencing problems testing a web site of mine that provides a CSV export for a report. He says the CSV is output to the screen, and no file is created.
It works fine on my IIS7, Vista, and IE7 setup. I can't get more details at the moment, but I'd like to at least ask: is my code, below, for sending the CSV adequate to be browser/version independent?
Response.Clear();
Response.Buffer = true;
Response.ContentType = "text/csv";
string fileName = GetExportFileName();
Response.AddHeader("Content-Disposition", "filename=" + fileName);
dt.WriteCsv(Response.Output, false);
Response.End();
I'm building fileName to include a date with /separators, which may be causing a problem, but it doesn't affect my machine, and the / gets automagically replaced with _.
I have also used
Response.AddHeader("content-disposition", "attachment;filename=FileName.csv");
which adds the "attachment" text. You might try that to see if it makes any difference for your friend.
There is a known problem in IE6 that do not correctly support the content-disposition meta tag and there are some gotchas in how to compose the various meta tags.
This link from Scott Hanselman details everything about the issue.
Regards
Massimo
Very late to the party very here, so this is more for anyone who came across this issue at a later time. This is in relation to quote "No HTTP header will force IE6 to offer a download."
In PHP I have the headers set as the following for IE to show a 'Save' button, and not just download the file - or display the file in the brower window.
Response.AddHeader("X-Download-Options", "noopen");
Response.AddHeader("X-Content-Type-Options", "nosniff");
The X headers are used to indicate that it is a non-standard header type. Works in IE6.
The only sure fire way to get IE to prompt for a download is to have the CSV file compressed (ie file.csv.zip or file.zip).
See
http://blogs.msdn.com/ie/archive/2005/02/01/364581.aspx
Handling MIME Types in Internet Explorer
MIME Type Detection in Internet Explorer
No HTTP header will force IE6 to offer a download. This is especially true for text content, which is 'auto-detected' by IE.
You can try with Content-Disposition attachment; filename=file.csv but I'm not certain it'll always work. If it does, please confirm.
You didn't mention what browser your friend is using. In the end, it could be a bug or non-standard behavior.
The following technique seems to work fine for me: http://www.blackbeltcoder.com/Articles/asp/creating-downloadable-content-dynamically.

Why does Response.Redirect close my browser window instead of redirecting?

For whatever reason when I use Response.Redirect the window just closes out instead of navigating to the given URL, here is the code.
if (mode == "print")
{
error_code.Text = "";
//thumb.Src = file_loc + "source/" + "certificate_thumbnail.jpeg";
link.HRef = "Certificates/" + u_name + ".pdf";
link.Visible = true;
Response.Redirect("http://xx.xxxxxxxxxxxxx.xx.gov/cert/Certificates/" + u_name + ".pdf");
}
(I removed the url for security purposes given who my client is...)
Maybe the Adobe Reader plugin is crashing the browser?
The problem is due to you opening an aspx page which contains the redirect to .pdf. As the aspx is pre-compiled when its opened by IE it EXPECTS text/html to come back - however as you've redirected its actually receiving application/pdf so IE craps itself and closes. Try it in firefox - works fine I bet.
I actually have the exact same problem at the moment and have yet to get a workaround. However check out this link https://stackoverflow.com/questions/400010/ie-closing-just-opened-popup-window theres some good stuff in there that may help.
Use Firebug in Firefox or a http debugging proxy like Fiddler for Internet Explorer to see exactly what the response of the server contains. Maybe the response isn't a PDF, but text/html which contains a Javascript window.close().
My guess is, that the code you posted isn't being executed for some reason and something else is happening.
What ever you have as your default PDF reader is likely causing this.
If you do
Response.Redirect("http://www.google.com");
What happens?
Try redirecting to a PDF that you know is valid. By searching google for PDF, I was able to find this PDF (http://www.utoronto.ca/cip/sa_ArtGt.pdf). So, if you redirect to that link does it still close the browser window? If it doesn't it's most likely related to your specific PDF file. If there's something wrong with your PDF File, try to regenerate it, if at all possible.

Resources