我有一个服务暴露2个端点,我想将消息格式化应用于其中一个端点。
为此,我希望捕获端点名称,以便仅为此特定端点应用MessageFormatter。
这是我的操作行为属性的代码:
public class JsonRpcMessageValidation : Attribute, IOperationBehavior
{
#region Properties
public Type serializeType { get; set; }
public Type deserializeType { get; set; }
#endregion
#region Constructors
/// <summary>
///
/// </summary>
/// <param name="serializeType">Serialize Type</param>
/// <param name="deserializeType">Deserialize Type</param>
public JsonRpcMessageValidation(Type serializeType, Type deserializeType)
{
this.serializeType = serializeType;
this.deserializeType = deserializeType;
}
#endregion
#region Methods
public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.ClientOperation clientOperation)
{
}
public void ApplyDispatchBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)
{
JsonRpcRequestMessageInspector jrrmInspector = new JsonRpcRequestMessageInspector();
dispatchOperation.ParameterInspectors.Add(jrrmInspector);
JsonRpcMessageFormatter jrmFormatter = new JsonRpcMessageFormatter(serializeType, deserializeType);
dispatchOperation.Formatter = jrmFormatter;
}
public void Validate(OperationDescription operationDescription)
{
}
#endregion
}
我在接口中使用此属性修饰方法,我需要Type信息,以便对传入和传出消息执行序列化和反序列化。
有没有人知道如何在代码中获取当前端点信息?
由于
答案 0 :(得分:1)
我能够解决这个问题:
我只是使用下面的方法从dispatchOperation中检索端点:
private static string GetCurrentEndpointName(System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)
{
string endpoint = String.Empty;
if (dispatchOperation.Parent.EndpointDispatcher.EndpointAddress.Uri.Segments.Count() > 0)
{
endpoint = dispatchOperation.Parent.EndpointDispatcher.EndpointAddress.Uri.Segments[dispatchOperation.Parent.EndpointDispatcher.EndpointAddress.Uri.Segments.Count() - 1];
}
return endpoint;
}
现在它将Message Formatters EXCLUSIVELY应用于ApplyDispatchBehavior方法中的端点“json”:
public void ApplyDispatchBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)
{
JsonRpcRequestMessageInspector jrrmInspector = new JsonRpcRequestMessageInspector();
dispatchOperation.ParameterInspectors.Add(jrrmInspector);
var endpoint = GetCurrentEndpointName(dispatchOperation);
//it only applies the Message Formatter to the 'json' endpoint
if (endpoint == "json")
{
JsonRpcMessageFormatter jrmFormatter = new JsonRpcMessageFormatter(serializeType, deserializeType);
dispatchOperation.Formatter = jrmFormatter;
}
}
答案 1 :(得分:0)
我认为使用IEndpointBehavior实现会更合适,您可以在需要自定义MessageFormatter的相应端点上使用它。
- larsw
答案 2 :(得分:0)
实际上我需要使用IOperationBehavior,因为我使用该属性来修饰方法,并且每个方法都有不同的请求和响应类型,我用它来对传入和传出的消息执行序列化和反序列化,否则是的,它会适合使用IEndpointBehavior。
THX