是否有可能向每个请求/消息发送一些上下文信息?例如。自动注入首选语言,在FrontEnd中选择用户并使其可用于任何请求,而无需为每个操作调用发送参数。
任何想法都表示赞赏。
答案 0 :(得分:1)
在客户端,添加端点行为:
public class AddHeaderBehavior : IEndpointBehavior
{
public void Validate(ServiceEndpoint endpoint)
{
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(new HeaderMessageInspector());
}
}
public class HeaderMessageInspector: IClientMessageInspector
{
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
var typedHeader = new MessageHeader<string>("my custom info");
var untypedHeader = typedHeader.GetUntypedHeader("myKey", "myNamespace");
request.Headers.Add(untypedHeader);
return null;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
}
}
在服务器端,添加服务行为:
public class AddHeaderBehavior : Attribute, IServiceBehavior
{
public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
foreach (var channelDispatcherBase in serviceHostBase.ChannelDispatchers)
{
var cDispatcher = (ChannelDispatcher)channelDispatcherBase;
foreach (var eDispatcher in cDispatcher.Endpoints)
{
eDispatcher.DispatchRuntime.MessageInspectors.Add(new OrganizationHeaderMessageInspector());
}
}
}
void IServiceBehavior.Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
}
}
public class HeaderMessageInspector : IDispatchMessageInspector
{
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
var header = request.Headers.GetHeader<string>("myKey", "myNamespace");
if (header != null)
{
OperationContext.Current.IncomingMessageProperties.Add("myKey", header);
}
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
}
}