I am recieving the "The root element is missing" error from my soap extension
while attempting to validate an incoming SOAP message request. I suspect the
problem resides in the ChainStream method but I'm not sure. Below is a
water-downed version of the code that I'm working on. While debugging, I
noticed that if I pass an invalid SOAP request, the schema validation catches
it and throws the error appropriately. However, when I pass in a valid SOAP
request, the root element error is returned but not from the validation
handler. With this, I don't believe the problem is arising from the
XmlValidatingReader process. Any advise on how to resolve this issue is
appreciated.
public class MySolSoapExtension : SoapExtension
{
private Stream inputStream;
private Stream outputStream;
private bool bPostDeserialize;
public override object GetInitializer( Type serviceType )
{
return GetType();
}
public override object GetInitializer( LogicalMethodInfo methodInfo,
SoapExtensionAttribute attribute )
{
return null;
}
public override void Initialize( object initializer )
{
bPostDeserialize = false;
return;
}
public override Stream ChainStream( Stream stream )
{
//This flag will be set to true during the AfterDeserialize handler in
ProcessMessage()
if( !bPostDeserialize)
{
this.inputStream = stream;
this.outputStream = new MemoryStream();
this.inputStream.Position = 0;
return outputStream;
}
else
{
this.inputStream = new MemoryStream();
this.outputStream = stream;
this.outputStream.Position = 0;
return inputStream;
}
}
public override void ProcessMessage(SoapMessage msg)
{
switch(msg.Stage)
{
case SoapMessageStage.BeforeDeserialize:
try
{
// read incoming xml soap message
XmlTextReader tr = new XmlTextReader(new StreamReader(msg.Stream));
// validate xml
XmlValidatingReader vr = new XmlValidatingReader(tr);
vr.ValidationType = ValidationType.Schema;
// create a schema collection
XmlSchemaCollection xsc = new XmlSchemaCollection();
xsc.Add("http://schemas.xmlsoap.org/soap/envelope/", "envelope.xml");
xsc.Add("http://schemas.xmlsoap.org/soap/encoding/", "encoding.xml");
// load schema collection
vr.Schemas.Add(xsc);
// add validation event handler
vr.ValidationEventHandler += new
ValidationEventHandler(reader_ValidationEventHandl er);
while (vr.Read());
vr.Close();
bPostDeserialize = true;
}
finally
{
// reset stream position
msg.Stream.Position = 0;
}
break;
case SoapMessageStage.AfterDeserialize:
break;
case SoapMessageStage.BeforeSerialize:
break;
case SoapMessageStage.AfterSerialize:
break;
}
}
private static void reader_ValidationEventHandler(object sender,
ValidationEventArgs e)
{
throw new SoapException("Schema Error: " + e.Exception.Message, new
XmlQualifiedName("qname"));
}
}