1
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;

        }

上面的代码屏幕截图帮助我根据架构验证客户端请求的消息,并在发生某些不一致时抛出错误。但我不知道如何将错误消息传递回 WCFservice,因为我也想将错误消息返回给客户端。

我尝试将错误消息添加到请求消息并返回到 WCF 服务。但是我不知道如何将错误消息放在正文内容中的父元素中,这对我来说很容易在服务操作中得到它。提前致谢!

4

0 回答 0