在自托管服务中,我希望使用App.config中指定的端点(如果存在),或者如果App.config为空,则使用代码中指定的默认端点。我该怎么做呢?
编辑:澄清一下,这是在服务器(服务)端使用ServiceHost。
一种方法是第一次尝试从配置文件中加载try
,并在catch
中硬编码端点。如:
MyServiceClient client = null;
try
{
client = new MyServiceClient();
}
catch (InvalidOperationException)
{
EndpointAddress defaultAddress = new EndpointAddress(...);
Binding defaultBinding = new Binding(...);
client = new MyServiceClient(defaultBinding, defaultAddress);
}
您可以获得如下配置部分:
var clientSection = System.Configuration.ConfigurationManager.GetSection("system.serviceModel/client");
如果value为null或clientSection.Endpoints
包含0个元素,则未定义
当我想实现没有app.config文件的独立服务客户端时,我遇到了同样的问题。终于我能理清头绪了。请遵循下面的代码示例。它工作正常,我已经测试过了。
BasicHttpBinding binding = new BasicHttpBinding();
binding.Name = "BasicHttpBinding_ITaskService";
binding.CloseTimeout = TimeSpan.FromMinutes(1);
binding.OpenTimeout = TimeSpan.FromMinutes(1);
binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
binding.SendTimeout = TimeSpan.FromMinutes(1);
binding.AllowCookies = false;
binding.BypassProxyOnLocal = false;
binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
binding.MaxBufferSize = 65536;
binding.MaxBufferPoolSize = 524288;
binding.MaxReceivedMessageSize = 65536;
binding.MessageEncoding = WSMessageEncoding.Text;
binding.TextEncoding = System.Text.Encoding.UTF8;
binding.TransferMode = TransferMode.Buffered;
binding.UseDefaultWebProxy = true;
binding.Security.Mode = BasicHttpSecurityMode.None;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
binding.Security.Transport.Realm = "";
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
binding.Security.Message.AlgorithmSuite = SecurityAlgorithmSuite.Default;
Uri endPointAddress = new Uri("http://www.kapanbipan.com/TaskService.svc");
ChannelFactory<taskmgr.TaskService.ITaskServiceChannel> factory = new ChannelFactory<ITaskServiceChannel>(binding, endPointAddress.ToString());
taskmgr.TaskService.ITaskServiceChannel client = factory.CreateChannel();
试试这个…未经测试,但应该适用于您。它将检查您的配置是否有任何具有匹配契约的端点。您可以将其更改为按名称匹配,返回不同的信息,或根据您的情况进行任何有意义的更改。如果没有找到匹配项,则可以放入逻辑来创建默认端点。
public List<EndpointAddress> GetEndpointAddresses(Type t)
{
string contractName = t.FullName;
List<EndpointAddress> endpointAddresses = new List<EndpointAddress>();
ServicesSection servicesSection = ConfigurationManager.GetSection("system.serviceModel/services") as ServicesSection;
foreach (ServiceElement service in servicesSection.Services)
{
foreach (ServiceEndpointElement endpoint in service.Endpoints)
{
if (string.Compare(endpoint.Contract, contractName) == 0)
{
endpointAddresses.Add(new EndpointAddress(endpoint.Address));
}
}
}
if (endpointAddresses.Count == 0)
{
//TODO: Add logic to determine default
endpointAddresses.Add(new EndpointAddress("Your default here"));
}
return endpointAddresses;
}