如何以编程方式创建此配置?

时间:2013-05-29 14:52:30

标签: c# wcf

我有一个WCF,我需要动态创建这个配置,因为我的 app.config永远不会在客户端计算机中更改。

有任何身体帮助吗?

<behaviors>
  <endpointBehaviors>
    <!-- REST -->
    <behavior name="restBehavior">
      <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped"/>
    </behavior>
  </endpointBehaviors>
  <serviceBehaviors>
    <behavior name="defaultBehavior">
      <serviceDebug includeExceptionDetailInFaults="true" />
      <serviceMetadata httpGetEnabled="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<client>
  <endpoint name="json" address="http://localhost:8080/json"
               binding="webHttpBinding"
               bindingConfiguration="webBinding"
               behaviorConfiguration="restBehavior"
               contract="ServiceReference.ServiceClientContract" />
</client>

1 个答案:

答案 0 :(得分:2)

配置文件中的大多数WCF元素都有一个可以在代码中设置的相应类或属性(大概是“动态”的意思?)例如,'endpointBehaviors'可以通过“行为”属性访问ServiceEndpoint类:

Uri baseAddress = new Uri("http://localhost:8001/Simple");
ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress);

ServiceEndpoint endpoint = serviceHost.AddServiceEndpoint(
    typeof(ICalculator),
    new WSHttpBinding(),
    "CalculatorServiceObject");

endpoint.Behaviors.Add(new MyEndpointBehavior());

Console.WriteLine("List all behaviors:");
foreach (IEndpointBehavior behavior in endpoint.Behaviors)
{
    Console.WriteLine("Behavior: {0}", behavior.ToString());
}

http://msdn.microsoft.com/en-us/library/system.servicemodel.description.serviceendpoint.behaviors.aspx

搜索您有兴趣在MSDN中配置的任何元素应该足以让您入门。