從許多地方借鑑,但大多是:
http://msmvps.com/blogs/paulomorgado/archive/2007/04/27/wcf-building-an-http-user-agent-message-inspector.aspx
我簡化了,但我覺得我有這將添加自定義httpheaders的實現。
public class HttpHeaderMessageInspector : IClientMessageInspector
{
private readonly Dictionary<string, string> _httpHeaders;
public HttpHeaderMessageInspector(Dictionary<string, string> httpHeaders)
{
this._httpHeaders = httpHeaders;
}
public void AfterReceiveReply(ref Message reply, object correlationState) { }
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
HttpRequestMessageProperty httpRequestMessage;
object httpRequestMessageObject;
if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
{
httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
foreach (var httpHeader in _httpHeaders)
{
httpRequestMessage.Headers[httpHeader.Key] = httpHeader.Value;
}
}
else
{
httpRequestMessage = new HttpRequestMessageProperty();
foreach (var httpHeader in _httpHeaders)
{
httpRequestMessage.Headers.Add(httpHeader.Key, httpHeader.Value);
}
request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
}
return null;
}
}
internal class HttpHeadersEndpointBehavior : IEndpointBehavior
{
private readonly Dictionary<string,string> _httpHeaders;
public HttpHeadersEndpointBehavior(Dictionary<string, string> httpHeaders)
{
this._httpHeaders = httpHeaders;
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { }
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
var inspector = new HttpHeaderMessageInspector(this._httpHeaders);
clientRuntime.MessageInspectors.Add(inspector);
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { }
public void Validate(ServiceEndpoint endpoint) { }
}
然後newing我的服務引用後:
var httpHeaders = new Dictionary<string, string>();
httpHeaders.Add("header1", "value1");
httpHeaders.Add("header2", "value2");
_serviceRef.Endpoint.Behaviors.Add(new HttpHeadersEndpointBehavior(httpHeaders));
閒來無事不得不改變。如果你想到一個更簡單的方法,讓我知道。
把這個解決方案放在答案中,而不是在問題中。 – 2012-07-18 15:52:50
http://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontext.outgoingmessageheaders(v=vs.90).aspx是一個簡單的解決方案。 – cederlof 2013-12-05 09:48:45
@cederlof,你的鏈接是參考SOAP標題。問題是關於HTTP標頭。 – NovaJoe 2014-09-29 17:25:31