【发布时间】: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() 或XmlTextWriter 在WriteToStreamAsync 方法中的某处关闭蒸汽有关。是否有其他方法来处理此代码?
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