如何在WCF中修改EndpointIdentity?ServiceHost修改无效问题
关于ServiceHost修改EndpointIdentity的解决方案
可以修改EndpointIdentity,但你当前的实现方式存在问题,导致修改未生效。以下是修正方案和原因说明:
问题原因
你在添加Endpoint后再修改其Address属性,此时WCF可能已经基于服务证书自动生成并缓存了默认的EndpointIdentity,后续修改无法覆盖这个默认值。
正确实现方式
在添加服务Endpoint时直接指定带有自定义DNS标识的EndpointAddress,而不是事后修改。这样WCF会直接使用你指定的标识,而非从证书提取默认值。
修正后的完整代码示例
// 先加载证书 var store = new X509Store(StoreName.My, location); store.Open(OpenFlags.ReadOnly); X509Certificate2 cert = store.Certificates.OfType<X509Certificate2>().FirstOrDefault( x => x.Thumbprint == thumbprint ); store.Close(); host.Credentials.ServiceCertificate.Certificate = cert; // 创建目标地址和自定义DNS标识 Uri dnsrelativeAddress = new Uri(host.BaseAddresses[0], "duplex"); EndpointAddress epa = new EndpointAddress(dnsrelativeAddress, EndpointIdentity.CreateDnsIdentity("identity.com")); // 添加Endpoint时直接使用带自定义标识的地址 var aa = host.AddServiceEndpoint( typeof(IDuplexService), netTcpBinding2, epa);
额外注意事项
- 确保所有Endpoint配置操作都在
ServiceHost.Open()之前完成,一旦Host启动,就无法再修改Endpoint的核心属性。 - 检查你的NetTcpBinding安全配置,确保其允许客户端使用指定的DNS标识进行验证。例如:
netTcpBinding2.Security.Mode = SecurityMode.Transport; netTcpBinding2.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;
内容的提问来源于stack exchange,提问作者Teppei Abe
相关产品推荐
相关产品推荐

