在较低级别上,您可以在IClientMessageInspector
的帮助下添加HTTP标头。尝试从this post on SL forum开始。
下一步取决于您的使用情况。
如果头部的值必须与DomainContext
调用的任何方法相同,那么您可以使用partial类扩展上下文,为头部值添加属性并在检查器中使用该属性。
如果您需要为每个方法调用传递不同的值,您可能需要将您的DomainContext
包装到另一个类中,并为上下文的每个方法添加一个参数,以接受标头值并将其传递给检查员莫名其妙。不用说,没有代码生成器,这将是困难的。
下面是来自SL论坛第一种情况的调整采样:我需要
public sealed partial class MyDomainContext
{
public string HeaderValue { get; set; }
partial void OnCreated()
{
WebDomainClient<IMyDomainServiceContract> webDomainClient = (WebDomainClient<IMyDomainServiceContract>)DomainClient;
CustomHeaderEndpointBehavior customHeaderEndpointBehavior = new CustomHeaderEndpointBehavior(this);
webDomainClient.ChannelFactory.Endpoint.Behaviors.Add(customHeaderEndpointBehavior);
}
}
public class CustomHeaderEndpointBehavior : IEndpointBehavior
{
MyDomainContext _Ctx;
public CustomHeaderEndpointBehavior(MyDomainContext ctx)
{
this._Ctx = ctx;
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { }
public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(new CustomHeaderMessageInspector(this._Ctx));
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher) { }
public void Validate(ServiceEndpoint endpoint) { }
}
public class CustomHeaderMessageInspector : IClientMessageInspector
{
MyDomainContext _Ctx;
public CustomHeaderMessageInspector(MyDomainContext ctx)
{
this._Ctx = ctx;
}
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState) {}
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)
{
string myHeaderName = "X-Foo-Bar";
string myheaderValue = this._Ctx.HeaderValue;
HttpRequestMessageProperty property = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
property.Headers[myHeaderName] = myheaderValue;
return null;
}
}
究竟是什么。事实上,我应该知道自从我使用WCF扩展点在服务器上做类似的事情。感谢Pavel !. –