:
public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
ServerMessageFormatter Formatter = new ServerMessageFormatter();
dispatchOperation.Formatter = Formatter;
}
在Formatter中我有空Deserialize方法因为我想使用默认行为
public void DeserializeRequest(System.ServiceModel.Channels.Message message, object[] parameters)
{}
但在序列化
中 public System.ServiceModel.Channels.Message SerializeReply(System.ServiceModel.Channels.MessageVersion messageVersion, object[] parameters, object result)
{
//some code
}
问题是在启用此类之后,service方法中的参数始终显示为null,但在IDispatchMessageInspector类中,我看到参数已正确发送。我不知道它为什么会发生,我只添加了这个消息格式化程序代码,Deserialize的空类可能导致这个吗?
答案 0 :(得分:2)
如果您未在DeserializeRequest
上提供自己的逻辑,则没有默认行为。您需要引用现有格式化程序并在ServerMessageFormater
中手动委派或提供自己的逻辑。
答案 1 :(得分:1)
当我们实现 IDispatchMessageFormatter 接口时,通常我们不认为方法 DeserializeRequest 很重要,因为它不返回任何数据。这是一种误导,因为方法需要做些事情。
使参数正确传递的最简单方法是使用基本 DispatchMessageFormatter 。将其添加到构造函数中。
public class ResponseJsonFormatter : IDispatchMessageFormatter
{
IDispatchMessageFormatter basicDispatchMessageFormatter;
OperationDescription Operation;
public ResponseJsonFormatter(OperationDescription operation, IDispatchMessageFormatter inner)
{
this.Operation = operation;
this.basicDispatchMessageFormatter = inner;
}
public void DeserializeRequest(Message message, object[] parameters)
{
basicDispatchMessageFormatter.DeserializeRequest(message, parameters);
}
public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
{
string json=Newtonsoft.Json.JsonConvert.SerializeObject(result);
byte[] bytes = Encoding.UTF8.GetBytes(json);
Message replyMessage = Message.CreateMessage(messageVersion, Operation.Messages[1].Action, new RawDataWriter(bytes));
replyMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
return replyMessage;
}
}
并以以下行为启动它:
public class ClientJsonDateFormatterBehavior : IOperationBehavior
{
public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
{
// throw new NotImplementedException();
}
public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
{
}
public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
dispatchOperation.Formatter = new ResponseJsonFormatter(operationDescription, dispatchOperation.Formatter);
}
public void Validate(OperationDescription operationDescription)
{
// throw new NotImplementedException();
}
}
您可以在github分支 DateTimeFormatterWithParams
中查看工作示例。