栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

WebAPI StreamContent与PushStreamContent

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

WebAPI StreamContent与PushStreamContent

关于这两种方法的内存使用情况,对于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");


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/381528.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号