2011-09-06 13 views
1

我有一個WCF服務,使文件的上傳,而無需使用MessageContract WCF服務。定義「的app.config」使用的WebHttpBinding

[OperationContract, WebInvoke(UriTemplate = "UploadFile?filename={filename}")] 
bool UploadFile(string filename, Stream fileContents); 

我被允許使用另外一個參數Stream對象旁邊,因爲它是UriTemplate的一部分。由於該服務作爲託管Windows服務運行,因此我必須手動啓動ServiceHost。

protected override void OnStart(string[] args) 
{ 
    FileServiceHost = new ServiceHost(typeof(FileService), new Uri("http://" + Environment.MachineName + ":8000/FileService")); 
    FileServiceHost.AddServiceEndpoint(typeof(IFile), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior()); 
    FileServiceHost.Open(); 
} 

有了這一切,服務啓動,並工作得很好。但是我想將上面的一些內容移到app.config文件中。要做到這一點,我註釋掉的OnStart第二線並與FileServiceHost = new ServiceHost(typeof(FileService))取代了第一道防線。然後,我添加了信息,以在app.config ...

<system.serviceModel> 

<services> 
    <service name="Test.Server.FileService" behaviorConfiguration="DefaultBehavior"> 
    <host> 
     <baseAddresses> 
     <add baseAddress="net.tcp://localhost:8000/FileService"/> 
     </baseAddresses> 
    </host> 
    <endpoint address="" binding="webHttpBinding" contract="IFile"/> 
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> 
    </service> 
</services> 

<behaviors> 
    <serviceBehaviors> 
    <behavior name="DefaultBehavior"> 
     <serviceMetadata httpGetEnabled="true"/> 
     <serviceDebug includeExceptionDetailInFaults="true"/> 
    </behavior> 
    </serviceBehaviors> 
</behaviors> 

忽然服務不能再啓動。它引發此異常的OnStart方法的FileServiceHost.Open:「對於請求在操作UploadFile是一個流的操作必須有一個類型爲流的單個參數」。

一定有什麼問題,我定義在app.config中的服務,因爲當我從那裏刪除它,一切正常的方式。我在這裏做錯了什麼?

回答

2

以下是我固定的問題通過將webHttpBinding添加到端點行爲。

添加behaviorConfiguration="TestBehavior"<endpoint address="" binding="webHttpBinding" contract="IFile"/>,然後定義TestBehavior如下:

<endpointBehaviors> 
    <behavior name="TestBehavior"> 
     <webHttp /> 
    </behavior> 
</endpointBehaviors> 
1

對於流在WCF啓用,有多種限制。其中之一是有Stream類型的單個參數(or any of two other types

這可能意味着,WCF「猜測」您試圖在合約您 將內容傳輸和默認的TransferModeStreamed(這純粹是一個這不是什麼證明文件說TransferMode默認爲Buffered

一種選擇是將傳輸模式在XML明確設置爲Buffered:。

<webHttpBinding> 
    <binding name="MyWebBinding" transferMode="Buffered"/> 
</webHttpBinding> 

但是,使用Buffered傳輸模式時,消息的內容在發送之前將被完全緩衝,這對大文件來說不是好事。

另一種選擇是使用Streamed傳輸模式。如果要傳輸文件的內容,並同時提供文件名,你必須定義一個自定義Message類,併發送文件的元數據在郵件標題:

[MessageContract] 
public class UploadFileMessage 
{ 
    [MessageHeader] 
    public string Filename { get; set; } 

    [MessageBodyMember] 
    public Stream Content { get; set; } 
} 
+0

我不能使用MessageContracts作爲SOAP不支持HTTP。無論哪種方式,似乎在端點上使用「WebHttpBehavior」可以解決問題。 – rafale

+0

很高興知道。然後,您可能需要發佈並接受您自己的問題答案。 –

相關問題