Thursday, January 28, 2010

Simple way to output XML in ASP.NET MVC

Another post to document something that I really don't want to have to look up ever again. I simply wanted to output XML to the browser window using ASP.NET MVC. Sounds easy, simply use:
 
public ContentResult Index() 
{ 
StringWriter writer = new StringWriter();
myXmlDocument.Save(writer); 
return this.Content(writer.ToString(), @"text/xml", writer.Encoding);
} 


But no luck; IE7's CSS would not display the XML since IIS ASP.NET defaults to UTF-16 and the previous page was UTF-8? Yes, both pages were correctly tagged with there encoding and correctly identified by IE as UTF-8 or UTF-16. It just wouldn't process the later. Whats up with that; can't these MS kids get along. So did a search and found a soluiton posted by Robert McLaw using a modified StringWriter that accepted an encoding which would worked very nicely:
 

public class StringWriterWithEncoding : StringWriter 
{ 
Encoding encoding; 
public StringWriterWithEncoding(Encoding encoding)
{ 
 this.encoding = encoding; 
}
public override Encoding Encoding 
{
 get { return encoding; } 
} 
}

To implement, just use the new writer and set it's encoding as desired:
 
public ContentResult Index() 
{ 
StringWriterWithEncoding writer = new StringWriterWithEncoding(Encoding.UTF8); 
myXmlDocument.Save(writer); 
return this.Content(writer.ToString(), @"text/xml", writer.Encoding);
} 

The advantatage of using the StringWriterWithEncoding method over a custom view is that the code can be used in other, non HTML based applications for consistency.