Visual Studio 2019 C#项目中为WCF请求添加SOAPHeader的方法求助
Hey there! No worries about being new—we all start somewhere. Let's break down how to add credentials and custom SOAP headers to your WCF proxy in Visual Studio 2019 (C#):
WCF makes it straightforward to attach credentials to your proxy, depending on the authentication type your server uses. Here are the most common scenarios:
For Username/Password Authentication
If your server expects a username and password, use the ClientCredentials property on your generated proxy:
// Initialize your generated proxy class var serviceProxy = new YourGeneratedServiceProxy(); // Set username and password serviceProxy.ClientCredentials.UserName.UserName = "your_username"; serviceProxy.ClientCredentials.UserName.Password = "your_password";
For Windows Domain Authentication
If the server uses Windows credentials, configure it this way:
serviceProxy.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("username", "password", "your_domain");
Since you mentioned using SOAPHeaderElement in Java, here are the equivalent approaches in C#—pick the one that fits your needs:
Option 1: Manual Header Addition (Per Request)
Use OperationContextScope to attach headers to individual service calls:
// Create your header content (can be a simple string or a complex object) var headerValue = "your_custom_header_data"; // Wrap the service call in an OperationContextScope using (new OperationContextScope(serviceProxy.InnerChannel)) { // Create the SOAP header var customHeader = MessageHeader.CreateHeader( "YourHeaderName", // Local name of the header "http://your-namespace.com", // Namespace matching the server's expectation headerValue); // Add the header to outgoing requests OperationContext.Current.OutgoingMessageHeaders.Add(customHeader); // Call your service method var response = serviceProxy.YourServiceMethod(); } // Clean up the proxy when done serviceProxy.Close();
Option 2: Global Header Injection (All Requests)
If you want the header attached to every request automatically, implement a IClientMessageInspector and IEndpointBehavior:
First, create the inspector to add headers:
public class CustomSoapHeaderInspector : IClientMessageInspector { public object BeforeSendRequest(ref Message request, IClientChannel channel) { // Create and add your header here var header = MessageHeader.CreateHeader( "YourHeaderName", "http://your-namespace.com", "persistent_header_value"); request.Headers.Add(header); return null; } public void AfterReceiveReply(ref Message reply, object correlationState) { // Optional: Handle response headers here } }
Then create a behavior to attach the inspector:
public class CustomHeaderBehavior : IEndpointBehavior { public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { clientRuntime.ClientMessageInspectors.Add(new CustomSoapHeaderInspector()); } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { } public void Validate(ServiceEndpoint endpoint) { } }
Finally, attach the behavior to your proxy:
var serviceProxy = new YourGeneratedServiceProxy(); serviceProxy.Endpoint.Behaviors.Add(new CustomHeaderBehavior()); // Set credentials as before serviceProxy.ClientCredentials.UserName.UserName = "username"; serviceProxy.ClientCredentials.UserName.Password = "password"; // All subsequent calls will automatically include the SOAP header var response = serviceProxy.YourServiceMethod(); serviceProxy.Close();
Option 3: Using Auto-Generated Header Classes (If WSDL Defines Headers)
If your WSDL explicitly defines the required SOAP headers, Visual Studio will generate corresponding classes when you add the service reference. You can simply set the property on your proxy:
var serviceProxy = new YourGeneratedServiceProxy(); // Assume the generated header class is `ServerRequiredHeader` serviceProxy.ServerRequiredHeaderValue = new ServerRequiredHeader { HeaderField1 = "value1", HeaderField2 = "value2" };
内容的提问来源于stack exchange,提问作者Elisa

