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

后端 未结 2 613
囚心锁ツ
囚心锁ツ 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:30

    Look at the accepted answer to this StackOverflow question. It shows how to programatically add client credentials to the proxy. It also shows adding the headers in the client endpoint configuration XML which I hadn't seen before.

    0 讨论(0)
  • 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<SecurityBindingElement>();
    // 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 = "...";
    
    0 讨论(0)
提交回复
热议问题