2010-01-26 58 views
21

我有以下XML配置如何在代碼而不是配置中創建WCF EndPointBehaviors?

<system.serviceModel> 
    <services> 
     <service name="MyService.MyServiceREST" behaviorConfiguration="MyServiceTypeBehaviors"> 
      <host> 
       <baseAddresses> 
        <add baseAddress="http://localhost:1234/MyService/xml"/> 
       </baseAddresses> 
      </host> 
      <endpoint address="" binding="webHttpBinding" behaviorConfiguration="xmlBehavior" contract="MyService.IMyService" /> 
     </service> 
    </services> 
    <behaviors> 
     <serviceBehaviors> 
      <behavior name="MyServiceTypeBehaviors" > 
       <serviceMetadata httpGetEnabled="true" /> 
       <serviceDebug includeExceptionDetailInFaults="True"/> 
      </behavior> 
     </serviceBehaviors> 
     <endpointBehaviors> 
      <behavior name="xmlBehavior"> 
       <webHttp/> 
      </behavior> 
     </endpointBehaviors> 
    </behaviors> 
</system.serviceModel> 

我想在C#代碼來實現,而不是使用的配置。

我找不出誰來用webHttp做EndPoint以將此服務公開爲REST服務。

ServiceHost serviceHost = new ServiceHost(singletonInstance, "http://localhost:1234/MyService/xml"); 

// Create Meta Behavior 
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); 
behavior.HttpGetEnabled = true; 

serviceHost.Description.Behaviors.Add(behavior); 

Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding(); 

serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex"); 

WSHttpBinding httpBinding = new WSHttpBinding(SecurityMode.None); 

serviceHost.AddServiceEndpoint(typeof(MyService.IMyService), httpBinding, "rest"); 

回答

38

通常情況下,與WCF做休息的時候,你可以使用<webHttp>行爲的配置,或者您可以使用WebServiceHost類(而不是「普通的香草」 ServiceHost)。使用WebServiceHost包括所有必要的調整和零件以使REST工作正常 - 不再需要webHttp行爲。

當然,這意味着,你需要一個單獨的WebServiceHost(在System.ServiceModel.Web),排它承載的服務爲REST。這可能是也可能不是你要找的內容:

WebServiceHost webServiceHost = 
    new WebServiceHost(singletonInstance, "http://localhost:1234/MyService/xml"); 

WebHttpBinding webBinding = new WebHttpBinding(); 
webServiceHost.AddServiceEndpoint(typeof(MyService.IMyService), webBinding, "rest"); 

你有另一種選擇是一個服務端點添加到您的定期服務的主機,只是配置上的端點的網絡行爲HTTP - 終點(和服務)的行爲都只是普通的.NET類的,畢竟,你可以實例,並添加到相應的Behaviors集合(該服務或單個端點):

WebHttpBinding restBinding = new WebHttpBinding(); 

ServiceEndpoint restSEP = 
    serviceHost.AddServiceEndpoint(typeof(MyService.IMyService), 
            restBinding, "rest"); 
restSEP.Behaviors.Add(new WebHttpBehavior()); 

這兩種方式應該帶你到你目標,我希望! (或至少讓你更接近:-)

+3

WebServiceHost工作。非常感謝!!! – 2010-01-26 21:49:48

+2

我想添加行爲restSEP.Behaviors.Add(新的WebHttpBehavior());'它的工作!謝謝! – 2013-07-24 15:53:30

相關問題