我有以下Xml配置
<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");
答案 0 :(得分:40)
通常,在使用WCF执行REST时,您可以在config中使用<webHttp>
行为,也可以使用WebServiceHost
类(而不是“普通的vanilla”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");
您拥有的另一个选项是将服务端点添加到常规服务主机,并在该端点上配置Web http行为 - 端点(和服务)行为毕竟是常规.NET类,您可以实例化,并添加到相应的Behaviors
集合(在服务或单个端点上):
WebHttpBinding restBinding = new WebHttpBinding();
ServiceEndpoint restSEP =
serviceHost.AddServiceEndpoint(typeof(MyService.IMyService),
restBinding, "rest");
restSEP.Behaviors.Add(new WebHttpBehavior());
我希望这两种方式都能带给你你的目标! (或者至少让你离得更近: - )