WCF-通过http上传流文件

WCF-通过http上传流文件,wcf,streaming,basichttpbinding,Wcf,Streaming,Basichttpbinding,我正在尝试构建一个WCF服务,允许我的WPF桌面客户端将文件上传到服务器 我改编了代码项目()中的一个代码示例,我也看了几篇SO文章,但似乎无法实现这一点 当我执行代码时,在服务器尝试读取已通过接口的流时,它会失败,并出现null引用异常 在这一点上,我相当迷茫,不知道如何解决这个问题。如有任何建议,我们将不胜感激 代码示例如下: CustomerDocumentModel是我与流一起通过WCF接口读取客户端文件的数据元素: [DataContract] [KnownType(typeof(Sy

我正在尝试构建一个WCF服务,允许我的WPF桌面客户端将文件上传到服务器

我改编了代码项目()中的一个代码示例,我也看了几篇SO文章,但似乎无法实现这一点

当我执行代码时,在服务器尝试读取已通过接口的流时,它会失败,并出现null引用异常

在这一点上,我相当迷茫,不知道如何解决这个问题。如有任何建议,我们将不胜感激

代码示例如下:

CustomerDocumentModel是我与流一起通过WCF接口读取客户端文件的数据元素:

[DataContract]
[KnownType(typeof(System.IO.FileStream))]
public class CustomerDocumentModel : IDisposable
{
    public CustomerDocumentModel()
    {
    }

    public CustomerDocumentModel(string documentName, string path)
    {
        DocumentName = documentName;
        Path = path;
    }

    [DataMember]
    public string DocumentName;

    [DataMember]
    public string Path;

    [DataMember]
    public System.IO.Stream FileByteStream;

    public void Dispose()
    { 
        if (FileByteStream != null)
        {
            FileByteStream.Close();
            FileByteStream = null;
        }
    }
}
IBillingService是我的WCF服务的接口定义:

[ServiceContract]
public interface IBillingService
{
    // other methods redacted...

    [OperationContract]
    void UploadCustomerDocument(CustomerDocumentModel model);
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class BillingService : IBillingService
{
    // Other methods redacted ...

    public void UploadCustomerDocument(CustomerDocumentModel model)
    {
        string path = HttpContext.Current.Server.MapPath(
            String.Format("/Documents/{1}",
                model.DocumentName));

        using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            const int bufferSize = 4096;
            byte[] buffer = new byte[bufferSize];

            int size = 0;
            try
            {
                // The following Read() fails with a NullReferenceException
                while ((size = model.FileByteStream.Read(buffer, 0, bufferSize)) > 0)
                {
                    stream.Write(buffer, 0, size);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
            stream.Close();
            model.FileByteStream.Close();
            }
        }
    }
}
BillingService类实现WCF服务:

[ServiceContract]
public interface IBillingService
{
    // other methods redacted...

    [OperationContract]
    void UploadCustomerDocument(CustomerDocumentModel model);
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class BillingService : IBillingService
{
    // Other methods redacted ...

    public void UploadCustomerDocument(CustomerDocumentModel model)
    {
        string path = HttpContext.Current.Server.MapPath(
            String.Format("/Documents/{1}",
                model.DocumentName));

        using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            const int bufferSize = 4096;
            byte[] buffer = new byte[bufferSize];

            int size = 0;
            try
            {
                // The following Read() fails with a NullReferenceException
                while ((size = model.FileByteStream.Read(buffer, 0, bufferSize)) > 0)
                {
                    stream.Write(buffer, 0, size);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
            stream.Close();
            model.FileByteStream.Close();
            }
        }
    }
}
我的WCF web服务器上的web.config中的一些相关位:

<system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime maxRequestLength="2097151" useFullyQualifiedRedirectUrl="true" executionTimeout="360"/>
</system.web>

<system.serviceModel>
    <serviceHostingEnvironment
        aspNetCompatibilityEnabled="true"
        multipleSiteBindingsEnabled="true" />
    <bindings>
        <basicHttpBinding>
            <binding name="userHttps" transferMode="Streamed" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
                <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
                <security mode="None" />
            </binding>
        </basicHttpBinding>
    </bindings>
    <behaviors>
        <serviceBehaviors>
            <behavior name="">
                <dataContractSerializer maxItemsInObjectGraph="2147483646"/>
                <serviceDebug includeExceptionDetailInFaults="true" />
                <serviceMetadata httpGetEnabled="true" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>

客户端是一个WPF/MVVM应用程序,它创建CustomerDocumentModel模型,使用OpenFileDialog()打开文件流,然后将模型传递给WCF服务上的UploadCustomerDocument方法


如果我遗漏了任何相关细节,请询问。

您的数据类型是导致流媒体失败的原因。这在MSDN中记录如下: 有关段落如下:

对流式传输的限制

使用流传输模式会导致执行运行时 附加限制

跨流传输发生的操作可以有一个协定 最多有一个输入或输出参数。该参数对应于 到消息的整个正文,并且必须是消息、派生的 流的类型,或IXmlSerializable实现。有回报 操作的值相当于有一个输出参数

一些WCF特性,如可靠的消息传递、事务和SOAP 消息级安全性,依靠缓冲消息进行传输。 使用这些功能可能会减少或消除性能优势 通过使用流媒体获得。要保护流式传输,请使用 仅传输级别安全性或使用传输级别安全性增强 仅验证消息安全性

SOAP头始终是缓冲的,即使在设置传输模式时也是如此 流。邮件的标题不得超过邮件的大小 MaxBufferSize传输配额。有关此的详细信息,请参见 设置,请参阅传输配额


我知道你的问题回答得很晚,我相信你一定也解决了你的问题。这可能对其他人有帮助:-)

在Datacontract上使用Messagecontract,并且只有一个具有datatype Stream和rest all参数的MessageBodyMember是MessageHeader。 以下是一个例子:

[MessageContract]

    public class CustomerDocumentModel : IDisposable
    {

        public CustomerDocumentModel(string documentName, string path)
        {
            DocumentName = documentName;
            Path = path;
        }

        [MessageHeader]
        public string DocumentName{get;set;}

        [MessageHeader]
        public string Path{get;set;}

        [MessageBodyMember]
        public System.IO.Stream FileByteStream{get;set;}

        public void Dispose()
        { 
            if (FileByteStream != null)
            {
                FileByteStream.Close();
                FileByteStream = null;
            }
        }
    }
注意:确保您的配置传输模式为StreamdResponse,并且您可能希望将MessageEncoding更改为MTOM以获得更好的性能

public void UploadCustomerDocument(CustomerDocumentModel model)
{
        var filename = //your file name and path;
        using (var fs = new FileStream(filename, FileMode.Create))

        {
               model.FileByteStream.CopyTo(fs);
        }
}

注意:解决方案不必是WCF。我也会考虑其他的C/ASP.NET解决方案。