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

前端 未结 5 1582
[愿得一人]
[愿得一人] 2020-12-17 16:17

I have a download link in my page, to a file I generate by the user request. Now I want to display the file size, so the browser can display how much is left to download. As

相关标签:
5条回答
  • 2020-12-17 16:18

    This should solve it as I think there's no need to use the FileStreamResult, when you can use the byte[] directly.

    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");
    }
    

    Note the FileContentResult return type.

    0 讨论(0)
  • 2020-12-17 16:28

    Can you please try the following code and see if that works?

    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");
    }
    

    "It works on my machine"

    And I've tried without the Content-length header and Fiddler reports a content length header anyway. I don't think it's needed.

    0 讨论(0)
  • 2020-12-17 16:35

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

    0 讨论(0)
  • 2020-12-17 16:38

    Try using

    HttpContext.Response.Headers.Add("Content-Length", file.Length.ToString());
    
    0 讨论(0)
  • 2020-12-17 16:41

    Not sure what else may be wrong there, but that content-length should be the size of the binary, not the string length.

    0 讨论(0)
提交回复
热议问题