【问题标题】:Web Api Caching and "Can't Access Closed Stream"Web Api 缓存和“无法访问封闭流”
【发布时间】:2014-05-18 09:32:45
【问题描述】:

我正在尝试将此缓存库用于 asp.net web api (https://github.com/filipw/AspNetWebApi-OutputCache)

安装它后,我收到了这个错误,并将其缩小到我的XmlMediaTypeFormatter 类中的一个类。

Cannot access a closed Stream

我相信这与Task.Factory.StarNew()XmlTextWriterWriteToStreamAsync 方法中的某处关闭蒸汽有关。是否有其他方法来处理此代码?

 public class CustomXmlFormatter : XmlMediaTypeFormatter 
    {
        public CustomXmlFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
            Encoding = new UTF8Encoding(false, true);
        }

        protected UTF8Encoding Encoding { get; set; }

        public override bool CanReadType(Type type)
        {
            if (type == null)
                return false;

            return true;
        }
        public override bool CanWriteType(Type type)
        {
            if (type == null)
                return false;

            return true;
        }

        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return Task.Factory.StartNew(() =>
            {
                using (var xmlr = new XmlTextReader(readStream))
                {
                    var serializer = new DataContractSerializer(type);
                    return serializer.ReadObject(xmlr);
                }
            });
        }

        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            var serializer = new DataContractSerializer(type, "Response", "");

            return Task.Factory.StartNew(() =>
            {
                using (var xmlw = new XmlTextWriter(writeStream, Encoding))
                {
                    xmlw.Formatting = Formatting.Indented;
                    serializer.WriteObject(xmlw, value);
                }
            });
        }
    }

【问题讨论】:

    标签: .net asp.net-mvc multithreading caching asp.net-web-api


    【解决方案1】:

    以下是 Web API 的 XmlMediaTypeFormatter 在写出 xml 时使用的 XmlWriterSettings

    var writerSettings = new XmlWriterSettings
    {
        OmitXmlDeclaration = true,
        CloseOutput = false,
        CheckCharacters = false
    };
    

    上述设置的使用如下...您也可以在您的情况下做类似的事情。

    var xmlWriter = XmlWriter.Create(writeStream, writerSettings);
    
    serializer.WriteObject(xmlWriter, value);
    

    仅供参考...上面的 sn-ps 代码取自 Web API 的 XmlMediaTypeFormatter...您可以查看它的源代码以获得更多想法...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-15
      • 2016-11-20
      • 2013-04-11
      相关资源
      最近更新 更多