关于这两种方法的内存使用情况,对于StreamContent和PushStreamContent,Web
API不会缓冲响应。以下代码快照来自WebHostBufferPolicySelector。源代码
在这里
。
/// <summary> /// Determines whether the host should buffer the <see cref="HttpResponseMessage"/> entity body. /// </summary> /// <param name="response">The <see cref="HttpResponseMessage"/>response for which to determine /// whether host output buffering should be used for the response entity body.</param> /// <returns><c>true</c> if buffering should be used; otherwise a streamed response should be used.</returns> public virtual bool UseBufferedOutputStream(HttpResponseMessage response) { if (response == null) { throw Error.ArgumentNull("response"); } // Any HttpContent that knows its length is presumably already buffered internally. HttpContent content = response.Content; if (content != null) { long? contentLength = content.Headers.ContentLength; if (contentLength.HasValue && contentLength.Value >= 0) { return false; } // Content length is null or -1 (meaning not known). // Buffer any HttpContent except StreamContent and PushStreamContent return !(content is StreamContent || content is PushStreamContent); } return false; }另外,PushStreamContent适用于需要将数据“推”到流中的场景,当StreamContent从流中“拉”数据时。因此,对于当前的文件下载情况,使用StreamContent应该可以。
以下示例:
// Here when the response is being written out the data is pulled from the file to the destination(network) streamresponse.Content = new StreamContent(File.OpenRead(filePath));// Here we create a push stream content so that we can use Xdocument.Save to push data to the destination(network) streamXdocument xDoc = Xdocument.Load("Sample.xml", LoadOptions.None);PushStreamContent xDocContent = new PushStreamContent((stream, content, context) =>{ // After save we close the stream to signal that we are done writing. xDoc.Save(stream); stream.Close();},"application/xml");


