在公开自托管服务时,从配置文件programmticlally读取WCF行为元素

Saw*_*wan 6 .net c# configuration wcf self-hosting

我在app.config中有这个配置:

    </binding>
  </basicHttpBinding>
</bindings>



<behaviors>
  <serviceBehaviors>
    <behavior name="myBehavior">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
Run Code Online (Sandbox Code Playgroud)

我想以编程方式从我的桌面应用程序公开此服务:

我定义了主机实例:

ServiceHost host = new ServiceHost(typeof(MyType), new Uri("http://" + hostName + ":" + port + "/MyName"));
Run Code Online (Sandbox Code Playgroud)

然后我用它的绑定添加端点:

var binding = new BasicHttpBinding("myBinding");
host.AddServiceEndpoint(typeof(IMyInterface), binding, "MyName");
Run Code Online (Sandbox Code Playgroud)

现在,我想用一些从配置文件中读取名为myBehavior的行为的代码替换下面的代码,而不是对行为选项进行硬编码.

ServiceMetadataBehavior smb = new ServiceMetadataBehavior() { HttpGetEnabled = true };    
host.Description.Behaviors.Add(smb);   
// Enable exeption details
ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
sdb.IncludeExceptionDetailInFaults = true;
Run Code Online (Sandbox Code Playgroud)

然后,我可以打开主机.

host.Open();
Run Code Online (Sandbox Code Playgroud)

*编辑*

使用配置文件配置服务

您不应该需要这种方式,您应该让主机从配置文件中自动获取其配置,而不是手动提供它们,阅读本文(使用配置文件配置服务),它将帮助您,我已经托管了我的服务C#中的单行和config中的少行.

这是关于(在代码中配置WCF服务)的第二篇文章,我的错是我试图混合两种方式!

我将添加此作为答案.

Mar*_*lig 7

首先,您需要使用打开配置文件

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Run Code Online (Sandbox Code Playgroud)

要么

var map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "app.config";
var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
Run Code Online (Sandbox Code Playgroud)

然后你读了行为:

var bindings = BindingsSection.GetSection(config);
var group = ServiceModelSectionGroup.GetSectionGroup(config);
foreach (var behavior in group.Behaviors.ServiceBehaviors)
{
    Console.WriteLine ("BEHAVIOR: {0}", behavior);
}
Run Code Online (Sandbox Code Playgroud)

请注意,这些都是类型System.ServiceModel.Configuration.ServiceBehaviorElement,所以不是你想要的.

如果您不介意使用私有API,可以BehaviorExtensionElement.CreateBehavior()通过反射调用受保护的方法:

foreach (BehaviorExtensionElement bxe in behavior)
{
    var createBeh = typeof(BehaviorExtensionElement).GetMethod(
        "CreateBehavior", BindingFlags.Instance | BindingFlags.NonPublic);
    IServiceBehavior b = (IServiceBehavior)createBeh.Invoke(bxe, new object[0]);
    Console.WriteLine("BEHAVIOR: {0}", b);
    host.Description.Behaviors.Add (b);
}
Run Code Online (Sandbox Code Playgroud)


Saw*_*wan 6

使用配置文件配置服务

您不应该需要这种方式,您应该让主机从配置文件中自动获取其配置,而不是手动提供它们,阅读本文(使用配置文件配置服务),它将帮助您,我已经托管了我的服务C#中的单行和config中的少行.

这是关于(在代码中配置WCF服务)的第二篇文章,我的错是我试图混合两种方式!

  • 除非您不想使用默认配置文件 (3认同)