使IIS托管的WCF服务流式传输正常运行

4

我有点卡住了...

我的目标非常简单:我想通过一个IIS托管(然后是Windows Azure)的WCF服务公开,通过该服务,我可以使用流式上传文件,并添加有关要上传的文件的一些元数据(文件名,MD5散列等常见信息...),并能够显示有关上传的准确进度信息。

首先,我创建了一个派生类StreamWithProgress,该类从FileStream继承,我已重写Read方法以引发每次读取时传递进度信息的事件。

其次,我使用MessageContract ( http://msdn.microsoft.com/en-us/library/ms730255.aspx ) 创建了一个WCF服务,将META数据和流对象包装到单个SOAP信封中。此服务非常简单,仅公开用于上传的单个方法。

我将所有缓冲区大小设置为接受大量数据,如下所示:

根据 httpRuntime 设置:

根据以下内容设置IIS\ASP兼容性设置:

根据以下内容禁用批处理:

我已经创建了一个自托管服务,上传成功。然后我将其“升级”为IIS托管服务(在我的本地机器上),它可以正常工作。接着我创建了一个本地托管的Windows Azure服务,其中包含一个WCF webrole,也可以正常工作。但问题在于,在所有实例中都没有进行实际的流式传输...在发送数据之前,所有实例都会缓冲数据。当我注意到客户端正在报告进度,但服务器直到整个文件被缓冲后才开始写入该文件时,我遇到了这个问题。以下是我的实际代码。有什么想法或帮助吗?任何东西都将不胜感激...谢谢!服务器web.config:
<?xml version="1.0"?>
<configuration>
    <system.serviceModel>

        <bindings>
            <basicHttpBinding>
                <binding name="uploadBasicHttpBinding" 
                 maxReceivedMessageSize="2147483647" 
                 transferMode="Streamed" 
                 messageEncoding="Mtom"
                 maxBufferPoolSize="2147483647"
                 maxBufferSize="2147483647">
                 <readerQuotas maxArrayLength="2147483647" 
                                maxBytesPerRead="2147483647" 
                                maxDepth="2147483647" 
                                maxNameTableCharCount="2147483647" 
                                maxStringContentLength="2147483647"/>
                </binding>
            </basicHttpBinding>
        </bindings>

            <behaviors>
                <serviceBehaviors>
                    <behavior name="defaultBehavior">
                        <serviceMetadata httpGetEnabled="true"/>
                        <serviceDebug includeExceptionDetailInFaults="false"/>
                        <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
                    </behavior>
                </serviceBehaviors>
            </behaviors>

        <!-- Add this for BufferOutput setting -->
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true"/>

        <services>
            <service name="WcfService1.Service1" behaviorConfiguration="defaultBehavior">           
                <endpoint binding="basicHttpBinding" contract="WcfService1.IService1" bindingConfiguration="uploadBasicHttpBinding"/>
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
            </service>
        </services>

    </system.serviceModel>

    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
    </system.webServer>

    <system.web>
        <compilation debug="true"/>
    <httpRuntime maxRequestLength="2147483647" />
    </system.web>

</configuration>

服务合同:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.IO;

namespace WcfService1
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract(IsOneWay=true)]
        void UploadStream(Encapsulator data);
    }
}

实际服务:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

using System.IO;
using System.Web;
using System.ServiceModel.Activation;

namespace WcfService1
{
    [MessageContract]
    public class Encapsulator
    {
        [MessageHeader(MustUnderstand = true)]
        public string fileName;
        [MessageBodyMember(Order = 1)]
        public Stream requestStream;
    }

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1 : IService1
    {
        public Service1()
        {
            HttpContext context = HttpContext.Current;

            if (context != null)
            {
                context.Response.BufferOutput = false;
            }
        }

        public void UploadStream(Encapsulator data)
        {
            const int BUFFER_SIZE = 1024;

            int bytesRead = 0;

            byte[] dataRead = new byte[BUFFER_SIZE];

            string filePath = Path.Combine(@"C:\MiscTestFolder", data.fileName);

            string logPath = Path.Combine(@"C:\MiscTestFolder", string.Concat(data.fileName, ".log"));

            bytesRead = data.requestStream.Read(dataRead, 0, BUFFER_SIZE);

            StreamWriter logStreamWriter = new StreamWriter(logPath);

            using (System.IO.FileStream fileStream = new System.IO.FileStream(filePath, FileMode.Create))
            {
                while (bytesRead > 0)
                {
                    fileStream.Write(dataRead, 0, bytesRead);
                    fileStream.Flush();

                    logStreamWriter.WriteLine("Flushed {0} bytes", bytesRead.ToString());
                    logStreamWriter.Flush();

                    bytesRead = data.requestStream.Read(dataRead, 0, BUFFER_SIZE);
                }

                fileStream.Close();
            }

            logStreamWriter.Close();
        }
    }
}

客户端 app.config:
<?xml version="1.0"?>
<configuration>
    <system.serviceModel>

        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IService1" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Mtom" textEncoding="utf-8" transferMode="Streamed"
                    useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <security mode="None">
                        <transport clientCredentialType="None" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>
            </basicHttpBinding>
        </bindings>

        <client>
            <endpoint address="http://localhost/WcfService1/Service1.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"
                contract="UploadService.IService1" name="BasicHttpBinding_IService1" />
        </client>

    </system.serviceModel>

    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    </startup>
</configuration>

客户端主要代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using CustomFileUploaderTester.UploadService;
using System.ServiceModel;
using System.IO;

namespace CustomFileUploaderTester
{
    class Program
    {
        private static long bytesRead = 0;

        static void Main(string[] args)
        {
            Service1Client client = new Service1Client();

            using (StreamWithProgress fstream = new StreamWithProgress(@"C:\BladieBla\someFile.wmv", FileMode.Open))
            {
                client.InnerChannel.AllowOutputBatching = false;

                fstream.ProgressChange += new EventHandler<StreamReadProgress>(fstream_ProgressChange);

                client.UploadStream("someFile.wmv", fstream);

                fstream.Close();
            }

            Console.ReadKey();
        }

        static void fstream_ProgressChange(object sender, StreamReadProgress e)
        {
            bytesRead += e.BytesRead;

            Console.WriteLine(bytesRead.ToString());
        }
    }
}

派生的 FileStream 类(StreamWithProgress

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace CustomFileUploaderTester
{
    public class StreamReadProgress : EventArgs
    {
        #region Public Properties

        public long BytesRead
        {
            get;
            set;
        }

        public long Length
        {
            get;
            set;
        }

        #endregion

        #region Constructor

        public StreamReadProgress(long bytesRead, long fileLength)
            : base()
        {
            this.BytesRead = bytesRead;

            this.Length = fileLength;
        }

        #endregion
    }

    public sealed class StreamWithProgress : FileStream
    {
        #region Public Events

        public event EventHandler<StreamReadProgress> ProgressChange;

        #endregion

        #region Constructor

        public StreamWithProgress(string filePath, FileMode fileMode)
            : base(filePath, fileMode)
        {
        }

        #endregion

        #region Overrides

        public override int Read(byte[] array, int offset, int count)
        {
            int bytesRead = base.Read(array, offset, count);

            this.RaiseProgressChanged(bytesRead);

            return bytesRead;
        }

        #endregion

        #region Private Worker Methods

        private void RaiseProgressChanged(long bytesRead)
        {
            EventHandler<StreamReadProgress> progressChange = this.ProgressChange;

            if (progressChange != null)
            {
                progressChange(this, new StreamReadProgress(bytesRead, this.Length));
            }
        }


        #endregion
    }
}

-- 更新:2012-04-20

在我安装了一个环回适配器之后,我使用RawCap跟踪了通信,并发现数据实际上是流式传输的,但是IIS服务器在调用Web方法之前会缓冲所有数据!

根据这篇文章:

http://social.msdn.microsoft.com/Forums/is/wcf/thread/cfe625b2-1890-471b-a4bd-94373daedd39

这是ASP.Net的行为,WCF继承了它...但他们正在讨论在.Net 4.5中修复这个问题 :|

如果有其他建议,将会很棒!

谢谢!


如果降低服务器端的MaxBufferSize属性,是否会产生任何影响? - RichBower
嗨,RichBower,谢谢你的建议...在你的帖子之后,我尝试了所有的ReaderQuota和Binding设置...但是都没有成功... - mnemonic
2个回答

3
您正在使用Mtom与流传输模式一起使用,这可能会导致问题。请尝试删除Mtom。实际上,Mtom是一个非常古老的标准。此外,在使用具有流传输模式的SOAP服务时,我们只能有一个类型为Stream的单个参数。我们不能使用自定义类型,如Encapsulator。
建议构建文件上传/下载服务的解决方案是使用REST。在.NET平台上构建REST服务的方法之一是使用ASP.NET Web API:http://www.asp.net/web-api。使用此API,我们不需要处理流传输模式。我们需要处理的是Range头。这篇博客文章可能有所帮助:http://blogs.msdn.com/b/codefx/archive/2012/02/23/more-about-rest-file-upload-download-service-with-asp-net-web-api-and-windows-phone-background-file-transfer.aspx。但请注意,该API尚未发布。如果您不想使用预发布产品,则可以使用其他技术,例如,您可以将MVC控制器用作REST服务,或使用WCF REST服务,或构建自定义HTTP处理程序等。如果要使用Stream,则需要自定义流。我想建议您查看http://blogs.msdn.com/b/james_osbornes_blog/archive/2011/06/10/streaming-with-wcf-part-1-custom-stream-implementation.aspx的示例。
此致
敬礼,
Ming Xu。

嗨明,谢谢回复!不幸的是,对我们来说使用REST不是一个选项,但还是感谢你提供的参考资料!我相信它最终会派上用场的! :) - mnemonic

3
经过一些严格的测试,我发现数据实际上正在被流传输。根据http://msdn.microsoft.com/en-us/library/ms733742.aspx,我将[MessageContract]属性应用于Encapsulator类,并成功发送一些有关文件的额外元数据。使用WireShark和RawCap,可以清楚地看到在读取流时,数据被发送了出去。
另一个问题是,在上传方法实际调用之前,服务器(使用IIS 7.5)会对正在流传输的数据进行缓存!这有点让人担忧,但根据http://social.msdn.microsoft.com/Forums/is/wcf/thread/cfe625b2-1890-471b-a4bd-94373daedd39,在.Net 4.5版本中已经修复了该问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接