Creating Headers (wsse) Section of WCF Client Programmatically in C#

后端 未结 2 639
囚心锁ツ
囚心锁ツ 2020-12-10 05:05

how do make a the following section of Service Settings of app.config in C# programmatically:

    
  

        
2条回答
  •  一个人的身影
    2020-12-10 05:40

    You don't have to configure header directly in this case because your scenario should be supported by BasicHttpBinding or CustomBinding directly.

    If you need to configure it from C# you must create binding in code:

    // Helper binding to have transport security with user name token
    BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential);
    binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
    // Rest of your binding configuration comes here
    
    // Custom binding to have access to more configuration details of basic binding
    CustomBinding customBinding = new CustomBinding(binding);
    SecurityBindingElement element = customBinding.Elements.Find();
    // Remove security timestamp because it is not used by your original binding
    element.IncludeTimestamp = false;
    
    EndpointAddress address = new EndpointAddress("https://...");
    
    ProxyWebServiceClient client = new ProxyWebServiceClient(customBinding, address);
    client.ClientCredentials.UserName.UserName = "...";
    client.ClientCredentials.UserName.Password = "...";
    

    Other solution is building custom binding directly instead of starting with basic binding:

    SecurityBindingElemetn securityElement = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
    securityElement.IncludeTimestamp = false; 
    TextMessageEncodingBindingElement encodingElement = new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8);
    HttpsTransportBindingElement tranportElement = new HttpsTransportBindingElement();
    
    // Other configurations of basic binding are divided into properties of 
    // encoding and transport elements
    
    CustomBinding customBinding = new CustomBinding(securityElement, encodingElement, transportElement);
    
    EndpointAddress address = new EndpointAddress("https://...");
    
    ProxyWebServiceClient client = new ProxyWebServiceClient(customBinding, address);
    client.ClientCredentials.UserName.UserName = "...";
    client.ClientCredentials.UserName.Password = "...";
    

提交回复
热议问题