簡體   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