如何以编程方式在托管服务上设置服务主体名称

时间:2009-08-31 08:22:26

标签: c# .net wcf wcf-client wcf-configuration

要使用配置文件执行上述操作,我会这样做:

<endpoint
  address="...."
  binding="netTcpBinding"
  bindingConfiguration="MyBinding"
  contract="IService1">
  <identity>
    <servicePrincipalName value="name"/>
  </identity>
</endpoint>

但是如何将其添加到下面的代码中?

Uri uri = new Uri("http://example.com/service");
ServiceHost host = new ServiceHost(typeof(Service1), uri);

NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.Message;
binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
host.AddServiceEndpoint(typeof(IService1), binding, uri);
host.Open();

1 个答案:

答案 0 :(得分:6)

这有点麻烦,你需要使用AddServiceEndpoint方法的返回值并在那里设置它:

ServiceEndpoint serviceEndpoint = host.AddServiceEndpoint(typeof(IService1), binding, uri);
EndpointAddress myEndpointAddress = new EndpointAddress(uri, EndpointIdentity.CreateSpnIdentity("YourIdentity"));
serviceEndpoint.Address = myEndpointAddress;