Caching the xml response from a HttpHandler
My HttpHandler looks like:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/xml";
XmlWriter writer = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8);
writer开发者_JS百科.WriteStartDocument();
writer.WriteStartElement("ProductFeed");
DataTable dt = GetStuff();
for(...)
{
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
}
How can I cache the entire xml document that I am generating?
Or do I only have the option of caching the DataTable object?
Several things:
- Do not use
XmlTextWriterunless you're still using .NET 1.1. UseXmlWriter.Create()instead. - Your use of the
XmlWriterneeds to be in ausingblock, or you'll have resource leaks when an exception is thrown. That's very bad for something like anHttpHandler, since it can be called many times. - You can create a
MemoryStreamto base yourXmlWriteron. Create the XML as you currently are, but when you're done, you can "rewind" theMemoryStreamby setting thePositionto 0. You can then write the contents of the stream to a file, or wherever you like.
加载中,请稍侯......
精彩评论