繁体   English   中英

如何在代码而不是配置中创建WCF EndPointBehaviors?

[英]How do I create WCF EndPointBehaviors in Code rather than the configuration?

我有以下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");

通常,在使用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());

我希望这两种方式都能带给你你的目标! (或者至少让你离得更近:-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM