开发者

ASP.Net MVC FilePathResult Failing in IE

开发者 https://www.devze.com 2022-12-18 14:47 出处:网络
I have a controller action that returns a pdf document. Depending on a site switch variable it will choose one of a number of source files, rename it and return it to the browser. This works perfectly

I have a controller action that returns a pdf document. Depending on a site switch variable it will choose one of a number of source files, rename it and return it to the browser. This works perfectly on Chrome and Firefox but, on IE8, the download dialog appears and then the following开发者_运维技巧 error messagebox...

"Internet Explorer cannot download FullTermsAndConditions from www.mydomain.com.

Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later."

This is my code...

public ActionResult FullTermsAndConditions()
{
  var targetFileName = LookupTargetFileName();
  var fullPath = System.IO.Path.Combine(DownloadsPath, LookupSourceFileName());
  var result = File(fullPath, "application/pdf");
  result.FileDownloadName = targetFileName;

  return result;
}

Can anyone see what I've done wrong?


Further information...

I added the following code to my controller to view the headers...

protected override void OnResultExecuted(ResultExecutedContext filterContext)
{
  base.OnResultExecuted(filterContext);

  WriteResponseHeadersToFile(@"C:\temp\ResponseHeaders.txt", filterContext.HttpContext.Response);
}

private static void WriteResponseHeadersToFile(string fileName, System.Web.HttpResponseBase response)
{
  using (StreamWriter writer = new StreamWriter(fileName, true))
  {
    writer.Write("Reponse started @ ");
    writer.WriteLine(DateTime.Now.ToShortTimeString());

    var allHeaders = response.Headers;

    for (int i = 0; i < allHeaders.Count; i++)
      writer.WriteLine("{0} = {1}", allHeaders.Keys[i], allHeaders[i]);

    writer.Close();
  }
}

This was the result...

Reponse started @ 09:02

Server = Microsoft-IIS/7.0

X-AspNetMvc-Version = 1.0

Content-Disposition = attachment; filename="Full Terms and Conditions.pdf"


Success!

The problem is with client-side caching. One of my parent controller classes had the following code (in an attempt to stop a user going 'back' once logged out)...

protected override void OnResultExecuted(ResultExecutedContext filterContext)
{
  base.OnResultExecuted(filterContext);

  Response.Buffer = true;
  Response.Cache.SetCacheability(HttpCacheability.NoCache);
  Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
  Response.Expires = -1500;
  Response.Cache.SetETag(DateTime.Now.Ticks.ToString());
}

If, in IE8, the file you're downloading cannot be opened in the browser it will attempt to save a temporary copy. This is in violation of the no-cache header. Removing this header solves the problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号