【问题标题】:How to add Headers in HTTPContext Response in ASP.NET MVC 3?如何在 ASP.NET MVC 3 中的 HTTPContext 响应中添加标头?
【发布时间】:2020-03-13 02:06:53
【问题描述】:

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

【问题讨论】:

    标签: c# asp.net-mvc-3


    【解决方案1】:

    尝试使用

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 当前在 HttpContext 中不存在。
      • 好的,然后忽略Current。只需在原始代码中使用AppendHeader 而不是AddHeader
      【解决方案3】:

      你能试试下面的代码,看看是否有效吗?

      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 无论如何都会报告内容长度标头。我认为不需要。

      【讨论】:

      • 您的示例有效,但是当我生成文件时,它不会发生。 ;/
      • 您是否检查过流实际上包含任何内容? sr.GetRecordFile(..) 返回 byte[],对吗?
      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

        不确定还有什么问题,但 content-length 应该是二进制文件的大小,而不是字符串的长度。

        【讨论】:

        • 其实里面的长度应该就是流的长度,也就是二进制的长度吧?
        猜你喜欢
        • 2012-06-01
        • 2015-06-12
        • 2012-02-06
        • 1970-01-01
        • 2021-02-10
        • 2016-12-06
        • 2013-04-12
        • 2018-04-23
        • 2013-04-06
        相关资源
        最近更新 更多