是否将控制器的操作中的XML作为ActionResult? [英] Return XML from a controller's action in as an ActionResult?
本文介绍了是否将控制器的操作中的XML作为ActionResult?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在ASP.NET MVC中从控制器的操作返回XML的最佳方式是什么?有一种很好的方法可以返回JSON,但不适用于XML。我是否真的需要通过视图路由XML,或者我是否应该采用非最佳的响应方式。写入它?
推荐答案
使用MVCContrib的XmlResult操作。
供参考的代码如下:
public class XmlResult : ActionResult { private object objectToSerialize; /// <summary> /// Initializes a new instance of the <see cref="XmlResult"/> class. /// </summary> /// <param name="objectToSerialize">The object to serialize to XML.</param> public XmlResult(object objectToSerialize) { this.objectToSerialize = objectToSerialize; } /// <summary> /// Gets the object to be serialized to XML. /// </summary> public object ObjectToSerialize { get { return this.objectToSerialize; } } /// <summary> /// Serialises the object that was passed into the constructor to XML and writes the corresponding XML to the result stream. /// </summary> /// <param name="context">The controller context for the current request.</param> 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); } } }
这篇关于是否将控制器的操作中的XML作为ActionResult?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文