c# - 公开自托管服务时以编程方式从配置文件中读取 WCF 行为元素

标签 c# .net wcf configuration self-hosting

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

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



<behaviors>
  <serviceBehaviors>
    <behavior name="myBehavior">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
</behaviors>

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

我定义主机实例:

ServiceHost host = new ServiceHost(typeof(MyType), new Uri("http://" + hostName + ":" + port + "/MyName"));

然后我添加端点及其绑定(bind):

var binding = new BasicHttpBinding("myBinding");
host.AddServiceEndpoint(typeof(IMyInterface), binding, "MyName");

现在,我想用一些代码替换以下代码,这些代码从配置文件中读取名为 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;

然后,我就可以打开主机了。

host.Open();

* 编辑 *

使用配置文件配置服务

你不应该需要这种方式,你应该让主机自动从配置文件中获取配置,而不是手动给它们,阅读this article (Configuring Services Using Configuration Files) ,它会对你有所帮助,我在 C# 中将我的服务托管在一行中,而在配置中则很少。

This is a second article about (Configuring WCF Services in Code) , 我的错是我试图混合这两种方式!

我会将其添加为答案。

最佳答案

首先,您需要使用以下任一方式打开配置文件

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

var map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "app.config";
var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

然后你阅读行为:

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

请注意,这些都是 System.ServiceModel.Configuration.ServiceBehaviorElement 类型,因此还不是您想要的。

如果您不介意使用私有(private) API,您可以通过反射调用 protected 方法 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);
}

关于c# - 公开自托管服务时以编程方式从配置文件中读取 WCF 行为元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14032875/

相关文章:

c# - 将列表框的选定项目传递到 xaml

c# - 从 GAC 动态加载最新的程序集版本

.net - 使用 .Net 应用程序部署 MySQL Server + DB

WCF 超时未得到遵守

c# - 解密SSIS密码节点

c# - 如何在 C# 中使用 EWS 托管 API 订购电子邮件

javascript - 只能通过一个提交按钮发布值

c# - .NET 4.5 和 .NET 4.5.1 是否默认启用 TLS 1.1 和 TLS 1.2?

c# - 用。。。来代替\

c# - 从 scriptcs 脚本使用 HttpClient