You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从数据库获取SOAP信封创建Message时遇Stream读取异常求助

解决从SOAP字符串创建Message时的"Stream does not support reading"异常

问题根源

你在GenerateXmlDictionaryReader方法中用using声明了MemoryStream,当方法返回XmlDictionaryReader时,using块已经执行完毕,底层流被自动释放。而XmlDictionaryReader依赖这个流进行后续读取操作,此时流已不可用,因此抛出Stream does not support reading异常。

修复代码

移除GenerateXmlDictionaryReader中的using语句,让XmlDictionaryReader接管流的生命周期(它会在自身被释放时关闭流)。同时,创建MemoryStream后需要重置流的位置到起始处,避免从流末尾开始读取:

public static Stream GenerateStreamFromString(string s)
{           
    var stream = new MemoryStream(Encoding.UTF8.GetBytes(s));
    stream.Position = 0; // 将流指针重置到起始位置
    return stream;          
}

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

资源管理优化

为了避免潜在的资源泄漏,建议在使用Message时用using包裹,Message释放时会自动关闭关联的XmlDictionaryReader,进而释放底层的MemoryStream:

using (var reader = GenerateXmlDictionaryReader(soapenv, XmlDictionaryReaderQuotas.Max))
using (var message = Message.CreateMessage(reader, int.MaxValue, MessageVersion.Soap11))
{
    // 在这里处理Message对象
}

内容的提问来源于stack exchange,提问作者Techno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 23:40:24