问题
I am new WCF service. Here I am trying to add wsse:Security UsernameToken Header in wcf request message but I don't know how to do that and the rest of the things. It would be much appreciated if someone could help on this. Thanks in advance.
回答1:
You can add a custom header by implementing the IDispatchMessageInspector interface. IDispatchMessageInspector is the interface implemented by the server. The client needs to implement the IClientMessageInspector interface.
Here is my Demo:
public class CustomMessageInspector : IDispatchMessageInspector
{
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
MessageHeader header = MessageHeader.CreateHeader("Username", "http://Username", "Username");
OperationContext.Current.OutgoingMessageHeaders.Add(header);
}
}
This is the header added in the SOAP message.If you need to add a header to the http request, refer to the following code:
public class CustomMessageInspector : IDispatchMessageInspector
{
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
WebOperationContext Context = WebOperationContext.Current;
Context.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
}
}
CustomMessageInspector implements the IDispatchMessageInspector interface, and adds a custom header to the message after getting the message, and also adds a custom header before sending the message.
[AttributeUsage(AttributeTargets.Interface)]
public class CustomBehavior : Attribute, IContractBehavior
{
public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
return;
}
public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
return;
}
public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
{
dispatchRuntime.MessageInspectors.Add(new CustomMessageInspector());
}
public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
{
return;
}
}
We add this interceptor to the behavior of the service.
Finally we apply Custombehavior to our service.
来源:https://stackoverflow.com/questions/62775143/usernametokenheader-for-wcf-service