tags:

views:

19

answers:

0

hi, actually I'm able to implement a username authentication mode through web.config, but now i would accomplish the same solution just only using code with netTcpBinding.

how can I transform the following section in c# code?

<behavior name="Service1Behavior">
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom"
                                    customUserNamePasswordValidatorType="ClassLibrary1.MyValidator, ClassLibrary1" />
            <serviceCertificate findValue="MyServerCert" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My" />
          </serviceCredentials>
        </behavior>
   </serviceBehaviors>
  </behaviors>
    <bindings>
      <netTcpBinding>
        <binding name="myBinding">
          <security mode="Message">
            <message clientCredentialType="UserName"/>
          </security>
        </binding>
      </netTcpBinding>
    </bindings>
  <services>
   <service behaviorConfiguration="Service1Behavior" name="Service1">
<endpoint address="" binding="netTcpBinding" contract="IService1" bindingConfiguration="myBinding">

I tries something like following, but It doesn't work:

Uri address = new Uri("net.tcp://localhost:12345");

NetTcpBinding bindingType = new NetTcpBinding();
bindingType.Security.Mode = SecurityMode.Message;
bindingType.Security.Message.ClientCredentialType = MessageCredentialType.UserName;

ServiceMetadataBehavior mBehavior = new ServiceMetadataBehavior();

sh = new ServiceHost(typeof(Service), address);
sh.Description.Behaviors.Add(mBehavior);

sh.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "MyServerCert2");
sh.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = System.ServiceModel.Security.UserNamePasswordValidationMode.Custom;

sh.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");
sh.AddServiceEndpoint(typeof(IService), bindingType, address);

sh.Open();//not open..