[英]Download a file in a specified stream?
我在Asp.Net MVC Web應用程序中。
對於特定操作,我必須返回從另一個內部服務器生成的文件。 該服務器需要一些Web用戶不擁有的憑據。 因此,Asp.net MVC服務器必須將其自身連接到該服務器,下載並將下載的文件發送到客戶端。
實際上,我是通過ActionResult來完成的:
public class ReportServerFileResult : FileResult
{
private readonly string _host;
private readonly string _domain;
private readonly string _userName;
private readonly string _password;
private readonly string _reportPath;
private readonly Dictionary<string, string> _parameters;
/// <summary>
/// Initializes a new instance of the <see cref="ReportServerFileResult"/> class.
/// </summary>
/// <param name="contentType">Type of the content.</param>
/// <param name="host">The host.</param>
/// <param name="domain">The domain.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="password">The password.</param>
/// <param name="reportPath">The report path.</param>
/// <param name="parameters">The parameters.</param>
public ReportServerFileResult(string contentType, String host, String domain, String userName, String password, String reportPath, Dictionary<String, String> parameters)
: base(contentType)
{
_host = host;
_domain = domain;
_userName = userName;
_password = password;
_reportPath = reportPath;
_parameters = parameters;
}
#region Overrides of FileResult
/// <summary>
/// Writes the file to the response.
/// </summary>
/// <param name="response">The response.</param>
protected override void WriteFile(HttpResponseBase response)
{
string reportUrl = String.Format("http://{0}{1}&rs:Command=Render&rs:Format=PDF&rc:Toolbar=False{2}",
_host,
_reportPath,
String.Join("", _parameters.Select(p => "&" + p.Key + "=" + p.Value)));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(reportUrl);
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential(_userName, _password, _domain);
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
Stream fStream = webResponse.GetResponseStream();
webResponse.Close();
fStream.CopyTo(response.OutputStream);
fStream.Close();
}
#endregion
}
但是我不喜歡如何管理流,因為(如果我正確理解的話),我們會檢索文件的完整流,然后開始將其發送給最終用戶。
但這意味着我們要在內存中加載整個文件,不是嗎?
所以我想知道是否可以向HttpWebRequest提供必須在其中寫入響應的流? 要直接將Web響應流傳輸到輸出?
可能嗎? 你還有其他主意嗎?
您已經在連接兩個流。 僅僅因為調用GetResponse()
不會將整個數據讀取到內存中。
當目標流可以接受寫入時, CopyTo()
應該根據需要從源流中讀取數據,具體取決於目標流的傳輸速度。
您是否有任何指標表明整個內容已被讀取到Web進程的內存中?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.