繁体   English   中英

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

[英]How to add Headers in HTTPContext Response in ASP.NET MVC 3?

我的页面中有一个下载链接,指向我根据用户请求生成的文件。 现在我想显示文件大小,这样浏览器就可以显示还有多少要下载。 作为一种解决方案,我想在请求中添加一个 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");
}

当我检查提琴手时,它没有显示 Content-Length header。 你们能帮帮我吗?

尝试使用

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

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

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

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 header 和提琴手报告内容长度 header 反正。 我认为不需要。

这应该可以解决它,因为我认为没有必要使用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返回类型。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM