如何在ASP.NET MVC 3中的HTTPContext响应中添加标题?

我的页面中有一个下载链接,是我通过用户请求生成的文件。 现在我想显示文件大小,因此浏览器可以显示剩余的下载量。 作为一个解决方案,我想在请求中添加一个Header会起作用,但现在我不知道该怎么做。

这是我的尝试代码:

public FileStreamResult DownloadSignalRecord(long id, long powerPlantID, long generatingUnitID) { SignalRepository sr = new SignalRepository(); var file = sr.GetRecordFile(powerPlantID, generatingUnitID, id); Stream stream = new MemoryStream(file); HttpContext.Response.AddHeader("Content-Length", file.Length.ToString()); return File(stream, "binary/RFX", sr.GetRecordName(powerPlantID, generatingUnitID, id) + ".rfx"); } 

当我检查fiddler时,它没有显示Content-Length标题。 你们能帮助我吗?

试试HttpContext.Current.Response.AppendHeader("Content-Length", contentLength);

尝试使用

 HttpContext.Response.Headers.add("Content-Length", file.Length.ToString()); 

你可以试试下面的代码,看看是否有效?

 public FileStreamResult Index() { HttpContext.Response.AddHeader("test", "val"); var file = System.IO.File.Open(Server.MapPath("~/Web.config"), FileMode.Open); HttpContext.Response.AddHeader("Content-Length", file.Length.ToString()); return File(file, "text", "Web.config"); } 

“它适用于我的机器”

我已经尝试过没有Content-length标题,Fiddler无论如何报告内容长度标题。 我不认为这是必要的。

这应该解决它,因为我认为没有必要使用FileStreamResult ,直接使用byte[]

 public FileContentResult DownloadSignalRecord(long id, long powerPlantID, long generatingUnitID) { SignalRepository sr = new SignalRepository(); var file = sr.GetRecordFile(powerPlantID, generatingUnitID, id); HttpContext.Response.AddHeader("Content-Length", file.Length.ToString()); return File(file, "binary/RFX", sr.GetRecordName(powerPlantID, generatingUnitID, id) + ".rfx"); } 

注意FileContentResult返回类型。

不确定那里还有什么可能是错的,但内容长度应该是二进制文件的大小,而不是字符串长度。