Internet Explorer error using Asp MVC 4.0 FileResult

后端 未结 3 483
逝去的感伤
逝去的感伤 2020-12-19 20:59

I have the following code, deployed on a https Asp site, build with MVC 4.0:

public FileResult ANotSoWorkingFunction(string filePath, string fileName)
{
 pat         


        
3条回答
  •  鱼传尺愫
    2020-12-19 21:18

    I think I also ran into your problem.

    I am also running IIS 7.5 and downloading a PDF through an action on an HTTPS request. For reasons I have yet to isolate, IIS 7.5 seems to be appending no-cache="Set-Cookie" to my Cache-Control response header regardless of what I set the Cache settings to on the Response. This was causing the fairly well documented no-cache issue on IE6, IE7, and IE8.

    To resolve this, I made a small wrapper around the FileContentResult that cleared the headers, called the parent, then set the Cacheability to 'Private'. This side-stepped IIS 7.5's insistence to add no-cache="Set-Cookie" to the header, and the file downloaded properly in all browsers I tested. If you want to emulate what I did, first, here's my FileContentResult wrapper.

    public class PdfContentResult : FileContentResult {
    
        public PdfContentResult(byte[] data) : base(data, "application/pdf") { }
    
        public PdfContentResult(byte[] data, string fileName) : this(data) {
            if (fileName == null) {
                throw new ArgumentNullException("fileName");
            }
    
            this.FileDownloadName = fileName;
        }
    
        public override void ExecuteResult(ControllerContext context) {
            context.HttpContext.Response.ClearHeaders();
    
            base.ExecuteResult(context);
    
            context.HttpContext.Response.Cache.SetCacheability(HttpCacheability.Private);
        }
    }
    

    Then I added an extension method to my ControllerExtensions so that it would be simple to find:

    public static class ControllerExtensions {
    
        public static PdfContentResult Pdf(this Controller controller, byte[] fileContents, string fileName) {
            return new PdfContentResult(fileContents, fileName);
        }
    
    }
    

    Finally, within the Action, I did the equivalent of this:

    public ActionResult MyGeneratedPdf() {
        byte[] myPdfContentInByteStream = GetPdfFromModel();
        return this.Pdf(myPdfContentInByteStream, "MyFile.pdf");
    }
    

    Obviously, if you're downloading all kinds of data types, you might not want to bind the workaround so closely to PDF.

提交回复
热议问题