Search code examples
c#asp.net.netasp.net-mvcwcf

System.NotSupportedException: Stream does not support reading


I have this code which gets soap envelope(varchar(max)) from DB and create a XmlDictionaryReader from that and the goal is to create Message(System.ServiceModel.Channels.Message).

This is the code

public static Stream GenerateStreamFromString(string s)
{           
    var stream = new MemoryStream(Encoding.UTF8.GetBytes(s));               
    return stream;          
}

public static XmlDictionaryReader GenerateXmlDictionaryReader(string s, XmlDictionaryReaderQuotas quota)
{           
    using (var stream = GenerateStreamFromString(s))
    {
        return XmlDictionaryReader.CreateTextReader(stream, quota);
    }           
}

and I am calling the above methods here

var reader = GenerateXmlDictionaryReader(soapenv, XmlDictionaryReaderQuotas.Max);                       
message = Message.CreateMessage(reader, int.MaxValue, MessageVersion.Soap11);

and I am getting this error

System.NotSupportedException: Stream does not support reading.
   at System.IO.__Error.ReadNotSupported()
   at System.IO.BufferedStream.Read(Byte[] array, Int32 offset, Int32 count)
   at System.Xml.EncodingStreamWrapper.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.Xml.XmlBufferReader.TryEnsureBytes(Int32 count)
   at System.Xml.XmlUTF8TextReader.BufferElement()
   at System.Xml.XmlUTF8TextReader.ReadStartElement()
   at System.Xml.XmlUTF8TextReader.Read()
   at System.Xml.XmlBaseReader.MoveToContent()
   at System.ServiceModel.Channels.StreamedMessage..ctor(XmlDictionaryReader reader, Int32 maxSizeOfHeaders, MessageVersion desiredVersion)
   at System.ServiceModel.Channels.Message.CreateMessage(XmlDictionaryReader envelopeReader, Int32 maxSizeOfHeaders, MessageVersion version)

and I have also verified the soapenv is not empty and is valid xml in the code. I have no clue how to resolve this. Please help.


Solution

  • using (var stream = GenerateStreamFromString(s))
    {
        return XmlDictionaryReader.CreateTextReader(stream, quota);
    }
    

    This using disposes (/closes) the stream as you exit the method in the return - your reader is sat atop a dead stream; that is why it isn't working. See L98 and L120 here. Remove the using.