Wcf OperationContextScope与MessageInputs
帮助我理解这两者之间的区别。根据我的说法,手术 无论您使用的.NET应用程序(如WCF、Console、Web等)如何,都可以使用ContextScope,只要您调用任何其他服务(如WCF或基于Java的服务)[在使用ASMX服务的情况下不起作用]将头添加到传出消息中,都可以使用ContextScopeWcf OperationContextScope与MessageInputs,wcf,soapheader,idispatchmessageinspector,operationcontext,iclientmessageinspector,Wcf,Soapheader,Idispatchmessageinspector,Operationcontext,Iclientmessageinspector,帮助我理解这两者之间的区别。根据我的说法,手术 无论您使用的.NET应用程序(如WCF、Console、Web等)如何,都可以使用ContextScope,只要您调用任何其他服务(如WCF或基于Java的服务)[在使用ASMX服务的情况下不起作用]将头添加到传出消息中,都可以使用ContextScope 如果是这样的话,那么为什么我们需要任何客户端的MessageInspector来添加头呢?OperationContextScope比MessageInspector简单得多。任何人都可以了解这
如果是这样的话,那么为什么我们需要任何客户端的MessageInspector来添加头呢?OperationContextScope比MessageInspector简单得多。任何人都可以了解这两种方法的正确用法吗?
客户端的IClientMessageInspector
和服务器端的IDispatchMessageInspector都擅长检查消息体,可能在发送前修改消息,或修改接收内容
以下是一个示例:
public class MyMessageInspector : IClientMessageInspector
{
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
// Inspect and/or modify the message here
MessageBuffer mb = reply.CreateBufferedCopy(int.MaxValue);
Message newMsg = mb.CreateMessage();
var reader = newMsg.GetReaderAtBodyContents().ReadSubtree();
XElement bodyElm = XElement.Load(reader);
// ...
reply = newMsg;
}
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
{
// Something could be done here
return null;
}
}
编写一个行为,以便将检查器轻松应用于客户端:
public class MyInspectorBehavior : IEndpointBehavior
{
#region IEndpointBehavior Members
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(
new MyMessageInspector()
);
}
public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{}
public void Validate(ServiceEndpoint endpoint)
{}
#endregion
}
使用以下行为:
ChannelFactory<IService1> cf =
new ChannelFactory<IService1>(
new BasicHttpBinding(),
"http://localhost:8734/DataService.svc");
cf.Endpoint.Behaviors.Add(
new MyInspectorBehavior()
);
OperationContextScope对于处理标头(添加、删除)非常有用
Juval Löwy的WCF服务编程附录B对OperationContextScope进行了很好的解释。
Juval的框架ServiceModelEx帮助使用OperationContextScopes
和GenericContext
类
请参见Juval的公司网站下载:
问候感谢Emmanuel的回复。我知道MessageInspectors纯粹是基于WCF的,OperationContextScope如何。这是否可以用于WCF以外的其他用途,如控制台应用程序等。例如,我的控制台应用程序正在调用基于java的web服务,其中需要存在一个标头,我是否可以在发送请求时使用OperationContextScope向其中添加标头?
[MyServiceInspectorBehavior]
public class ServiceImpl : IService1
{ ...}