void validateMessage(ref System.ServiceModel.Channels.Message message)
{
XmlDocument bodyDoc = new XmlDocument();
var body = message.GetReaderAtBodyContents();
bodyDoc.Load(body);
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas = schemas;
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
XmlReader reader = XmlReader.Create(new XmlNodeReader(bodyDoc), settings);
while (reader.Read()) ; // do nothing, just validate
// Create new message
Message newMsg = Message.CreateMessage(message.Version, null,
new XmlNodeReader(bodyDoc.DocumentElement));
newMsg.Headers.CopyHeadersFrom(message);
foreach (string propertyKey in message.Properties.Keys)
newMsg.Properties.Add(propertyKey, message.Properties[propertyKey]);
// Close the original message and return new message
message.Close();
message = newMsg;
}
private static void ValidationCallBack(object sender, ValidationEventArgs e)
{
Console.WriteLine("Validation Error: {0}", e.Message);
//throw new RequestValidationFault(e.Message);
throw new FaultException<string>(e.Message);
}
object IDispatchMessageInspector.AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{
try
{
validateMessage(ref request);
}
catch (FaultException e)
{
throw new FaultException<string>(e.Message);
}
return null;
}
上面的代码截图帮助我验证客户端针对模式请求的消息,并在发生某些不一致时抛出错误。但我不知道如何将错误消息传递回WCF服务,因为我也想将错误消息返回给客户端。
我尝试将错误消息添加到请求消息并返回到WCF服务。但我不知道如何将错误消息放入正文内容中的父元素,这很容易让我在服务操作中得到它。提前谢谢!