从ASP.NET MVC中的控制器操作返回XML的最佳方法是什么?返回JSON有一种很好的方法,但不适用于XML.我是否真的需要通过View路由XML,还是应该采用Response.Write-it的非最佳实践方式?
return this.Content(xmlString, "text/xml");
使用MVCContrib的XmlResult Action.
这里参考的是他们的代码:
public class XmlResult : ActionResult { private object objectToSerialize; ////// Initializes a new instance of the /// The object to serialize to XML. public XmlResult(object objectToSerialize) { this.objectToSerialize = objectToSerialize; } ///class. /// /// Gets the object to be serialized to XML. /// public object ObjectToSerialize { get { return this.objectToSerialize; } } ////// Serialises the object that was passed into the constructor to XML and writes the corresponding XML to the result stream. /// /// The controller context for the current request. public override void ExecuteResult(ControllerContext context) { if (this.objectToSerialize != null) { context.HttpContext.Response.Clear(); var xs = new System.Xml.Serialization.XmlSerializer(this.objectToSerialize.GetType()); context.HttpContext.Response.ContentType = "text/xml"; xs.Serialize(context.HttpContext.Response.Output, this.objectToSerialize); } } }
如果您使用优秀的Linq-to-XML框架构建XML,那么这种方法将会很有帮助.
我XDocument
在动作方法中创建了一个.
public ActionResult MyXmlAction()
{
// Create your own XDocument according to your requirements
var xml = new XDocument(
new XElement("root",
new XAttribute("version", "2.0"),
new XElement("child", "Hello World!")));
return new XmlActionResult(xml);
}
这个可重用的自定义ActionResult
为您序列化XML.
public sealed class XmlActionResult : ActionResult
{
private readonly XDocument _document;
public Formatting Formatting { get; set; }
public string MimeType { get; set; }
public XmlActionResult(XDocument document)
{
if (document == null)
throw new ArgumentNullException("document");
_document = document;
// Default values
MimeType = "text/xml";
Formatting = Formatting.None;
}
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Clear();
context.HttpContext.Response.ContentType = MimeType;
using (var writer = new XmlTextWriter(context.HttpContext.Response.OutputStream, Encoding.UTF8) { Formatting = Formatting })
_document.WriteTo(writer);
}
}
您可以指定MIME类型(例如application/rss+xml
)以及是否需要缩进输出.这两个属性都有合理的默认值.
如果您需要UTF8以外的编码,那么为此添加属性也很简单.
如果您只想通过请求返回xml,并且您拥有xml"chunk",那么您可以这样做(作为控制器中的操作):
public string Xml() { Response.ContentType = "text/xml"; return yourXmlChunk; }
MVC Contrib中有一个XmlResult(以及更多).请访问http://www.codeplex.com/MVCContrib