c# – 在公开自托管服务时,从配置文件programmticlally读取WCF行
我在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")); 然后我用它的绑定添加端点: 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类型,所以还不是你想要的. 如果您不介意使用私有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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |