我在一个 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 响应直接流式传输到输出?
是否可以?你有别的想法吗?