在ASP中,从控制器的操作返回XML的最佳方式是什么.网络MVC?有一种很好的方法可以返回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);
        }
    }
}

Asp.net相关问答推荐

我可以将图像添加到 ASP.NET 按钮吗?

是否可以使用 Membership API 更改用户名

如何判断 IIS 是处于 32 位还是 64 位模式

文本框的输入按键触发事件

这两种方法有什么区别?

HttpContext.Current.Request.IsAuthenticated 和 HttpContext.Current.User.Identity.IsAuthenticated 有什么区别?

如何在 ASP.NET 应用程序中使用 jQuery 捕获提交事件?

什么时候不应该使用 Web 服务?

ASP.Net 自定义客户端验证

如何设置默认页面 asp.net

如何在 IIS 7.5 上使用 ASP.NET 表单身份验证保护静态文件?

将通用列表绑定到转发器 - ASP.NET

什么是实体框架中的复杂类型以及何时使用它?

ASP.NET MVC 2.0 JsonRequestBehavior 全局设置

如何在我自己的方法中模仿 string.Format()?

OWIN 和 Katana,为什么要将应用程序与服务器解耦?

远程计算机无法连接到 Visual Studio Web 服务器

当用户在文本框中按 Enter 键时执行按钮单击事件

如何使用 jquery 设置单选按钮 Select 的值

Windows 身份验证在本地 IIS 7.5 上不起作用.错误 401.1