On the client-side, we can modify the header through IClientMessageInspector,here is a demo:
public class ClientMessageLogger : IClientMessageInspector
{
public void AfterReceiveReply(ref Message reply, object correlationState)
{
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
HttpRequestMessageProperty header;
if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
{
header = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
}
else
{
header = new HttpRequestMessageProperty();
request.Properties.Add(HttpRequestMessageProperty.Name, header);
}
header.Headers["Host"] = "localhost";
return null;
}
}
ClientMessageLogger implements the IClientMessageInspector interface, and I modify its request header before the client post a request.
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class, AllowMultiple = false)]
public class CustContractBehaviorAttribute : Attribute, IContractBehavior, IContractBehaviorAttribute, IOperationBehavior
{
public Type TargetContract => throw new NotImplementedException();
public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
return;
}
public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
{
throw new NotImplementedException();
}
public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.ClientMessageInspectors.Add(new ClientMessageLogger());
}
public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
{
throw new NotImplementedException();
}
public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
{
}
public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
}
public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
{
return;
}
public void Validate(OperationDescription operationDescription)
{
throw new NotImplementedException();
}
}
We add the ClientMessageLogger to the client's behavior.
[CustContractBehavior]
public interface IService
{...}
Finally, we add this behavior to the interface of the service.