c# - Firefox 忽略 Response.ContentType

标签 c# .net asp.net httpwebrequest

我有以下代码,这些代码实质上是将文件从一台服务器“代理”到另一台服务器。它在 IE 中完美运行,但 Firefox 似乎忽略了 Content-Type header 并始终将文件 (MP3) 作为 text/html 传输。

这不是主要问题,但我想让它在所有浏览器中正常工作,所以有人可以提供帮助吗?另外,如果有更好/更有效的方法来完成此操作,请发布!

FileInfo audioFileInfo = new FileInfo(audioFile);
HttpWebRequest downloadRequest = (HttpWebRequest) WebRequest.Create(audioFile);
byte[] fileBytes;

using (HttpWebResponse remoteResponse = (HttpWebResponse) downloadRequest.GetResponse())
{
  using (BufferedStream responseStream = new BufferedStream(remoteResponse.GetResponseStream()))
  {
    fileBytes = new byte[remoteResponse.ContentLength];
    responseStream.Read(fileBytes, 0, fileBytes.Length);

    Response.ClearContent();
    // firefox seems to ignore this...
    Response.ContentType = Utilities.GetContentType(audioFileInfo);
    // ... and this
    //Response.ContentType = remoteResponse.ContentType;
    Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", audioFileInfo.Name));
    Response.AddHeader("Content-Length", remoteResponse.ContentLength.ToString());
    Response.BinaryWrite(fileBytes);
    Response.End();
  }
}

最佳答案

尝试在调用 ClearContents() 之前添加一个 Response.ClearHeaders(),就像提到的 x2 并将文件作为 application/octet-stream 发送:

Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=\"blah\""); 
...

当我需要将可下载文件(不一定是 mp3)传输到客户端时适合我。

关于c# - Firefox 忽略 Response.ContentType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1345355/

相关文章:

c# - Java 增强的 for 循环 VS .NET foreach 循环

c# - 更改AudioSource音量

c# - 如何在 asp.net 下载文件之前调用 javascript 函数?

c# - UserManager.IsInRoleAsync 和 UserManager.GetRolesAsync 彼此不一致

c# - 加载字节数组程序集

c# - 我们如何将嵌入式资源添加到在运行时从源文件编译的文件中

.net - AWS Polly 集成 SDK

c# - MVC 4 如何显示注解

asp.net - 存储站点配置数据的最佳方式是什么?

c# - asp.Net 中 DateTime 的默认时区