WebAPI StreamContent vs PushStreamContent

前端 未结 1 970
渐次进展
渐次进展 2020-11-27 04:12

I\'m implementing a MVC4 + WebAPI version of the BluImp jQuery File Upload all works well with my initial attempt but Im trying to ensure the best use of memory whilst downl

相关标签:
1条回答
  • 2020-11-27 04:38

    Regarding the memory usage of these both approaches, for StreamContent and PushStreamContent, Web API doesn't buffer the responses. Following snapshot of code is from WebHostBufferPolicySelector. Source code here.

        /// <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;
        }
    

    Also PushStreamContent is for scenarios where you need to 'push' data to the stream, where as StreamContent 'pulls' data from the stream. So, for your current scenario of downloading files, using StreamContent should be fine.

    Examples below:

    // Here when the response is being written out the data is pulled from the file to the destination(network) stream
    response.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) stream
    XDocument 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");
    
    0 讨论(0)
提交回复
热议问题