重工电子论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz
查看: 4532|回复: 0
打印 上一主题 下一主题

Asp.net mvc返回Xml结果,扩展Controller实现XmlResult以返回XML格式数据

[复制链接]

299

主题

684

帖子

6998

积分

学生管理组

Rank: 8Rank: 8

积分
6998
跳转到指定楼层
楼主
发表于 2017-11-23 22:34:01 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
这个帖子很清楚的说明了actionresult的原理

http://www.cnblogs.com/xiongzaiqiren/p/XmlResult.html

----------------------------------------------------------------------------------------------------------
我们都知道Asp.net MVC自带的Action可以有多种类型,比如ActionResult,ContentResult,JsonResult……,但是很遗憾没有支持直接返回XML的XmlResult。

当然,你也可以用ActionResult或者ContentResult,然后直接返回xml字符串。

如果我们想要想JsonResult一样来调用和返回xml结果,我们可以自己新建扩展XmlResult,该怎么办呢?不多说,看下面实例:

第一步,扩展System.Web.Mvc XmlRequestBehavior
[C#] syntaxhighlighter_viewsource syntaxhighlighter_copycode
/// <summary>
/// 扩展System.Web.Mvc XmlRequestBehavior
/// 指定是否允许来自客户端的HTTP GET请求
/// 熊仔其人/// </summary>
public enum XmlRequestBehavior
{
    /// <summary>
    /// HTTP GET requests from the client are allowed.
    /// 允许来自客户端的HTTP GET请求
    /// </summary>      
    AllowGet = 0,
    /// <summary>
    /// HTTP GET requests from the client are not allowed.
    /// 不允许来自客户端的HTTP GET请求
    /// </summary>
    DenyGet = 1,
}


第二步,实现XmlResult继承ActionResult
[C#] syntaxhighlighter_viewsource syntaxhighlighter_copycode
/// <summary>
/// 实现XmlResult继承ActionResult
/// 扩展MVC的ActionResult支持返回XML格式结果
/// 熊仔其人/// </summary>
public class XmlResult : ActionResult
{
    /// <summary>
    /// Initializes a new instance of the System.Web.Mvc.XmlResult class
    /// 初始化
    /// </summary>         
    public XmlResult() { }
    /// <summary>
    /// Encoding
    /// 编码格式
    /// </summary>
    public Encoding ContentEncoding { get; set; }
    /// <summary>
    /// Gets or sets the type of the content.
    /// 获取或设置返回内容的类型
    /// </summary>
    public string ContentType { get; set; }
    /// <summary>
    /// Gets or sets the data
    /// 获取或设置内容
    /// </summary>
    public object Data { get; set; }
    /// <summary>
    /// Gets or sets a value that indicates whether HTTP GET requests from the client
    /// 获取或设置一个值,指示是否HTTP GET请求从客户端
    /// </summary>
    public XmlRequestBehavior XmlRequestBehavior { get; set; }
    /// <summary>
    /// Enables processing of the result of an action method by a custom type that
    /// 处理结果
    /// </summary>
    /// <param name="context"></param>
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null) { throw new ArgumentNullException("context"); }
        HttpRequestBase request = context.HttpContext.Request;
        if (XmlRequestBehavior == XmlRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException("XmlRequest_GetNotAllowed");
        }
        HttpResponseBase response = context.HttpContext.Response;
        response.ContentType = !string.IsNullOrEmpty(this.ContentType) ? this.ContentType : "application/xml";
        if (this.ContentEncoding != null)
        {
            response.ContentEncoding = this.ContentEncoding;
        }
        if (Data != null)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                XmlSerializer xs = new XmlSerializer(Data.GetType());
                xs.Serialize(ms, Data); // 把数据序列化到内存流中                     
                ms.Position = 0;
                using (StreamReader sr = new StreamReader(ms))
                {
                    context.HttpContext.Response.Output.Write(sr.ReadToEnd()); // 输出流对象 
                }
            }
        }
    }
}

注释:如果想要修改反序列化后的xml命名空间,可以使用自定义命名空间:
[C#] syntaxhighlighter_viewsource syntaxhighlighter_copycode
//使用你的定义的命名空间名称
var ns = new XmlSerializerNamespaces();
ns.Add("xsi", "http://api.xxxx.com/1.0/");

然后这里添加自定义命名空间,注意第三个参数
xs.Serialize(ms, Data ,ns); // 把数据序列化到内存流中


第三步,扩展System.Mvc.Controller
[C#] syntaxhighlighter_viewsource syntaxhighlighter_copycode
/// <summary>
/// 扩展System.Mvc.Controller
/// 熊仔其人/// </summary>
public static class ControllerExtension
{
    public static XmlResult Xml(this Controller request, object obj) { return Xml(obj, null, null, XmlRequestBehavior.DenyGet); }
    public static XmlResult Xml(this Controller request, object obj, XmlRequestBehavior behavior) { return Xml(obj, null, null, behavior); }
    public static XmlResult Xml(this Controller request, object obj, Encoding contentEncoding, XmlRequestBehavior behavior) { return Xml(obj, null, contentEncoding, behavior); }
    public static XmlResult Xml(this Controller request, object obj, string contentType, Encoding contentEncoding, XmlRequestBehavior behavior) { return Xml(obj, contentType, contentEncoding, behavior); }

    internal static XmlResult Xml(object data, string contentType, Encoding contentEncoding, XmlRequestBehavior behavior) { return new XmlResult() { ContentEncoding = contentEncoding, ContentType = contentType, Data = data, XmlRequestBehavior = behavior }; }
}

到此就完成啦,下面就看看怎么调用:
第四步,在Controller里调用XmlResult
[C#] syntaxhighlighter_viewsource syntaxhighlighter_copycode
public ActionResult GetActionResult(string type)
{
    var data = new List<string>(); //注意,data必须是可被序列化的内容
    data.Add("A");
    data.Add("B");
    data.Add("C");

    if (type.ToLower() == "xml")
    {
        return this.Xml(data, XmlRequestBehavior.AllowGet);
    }
    else if (type.ToLower() == "json")
    {
        return Json(data, JsonRequestBehavior.AllowGet);
    }
    else {                  //error messages              
        return View("不支持此方法");
    }
}

public XmlResult GetXml()
{
    var data = new List<string>(); //注意,data必须是可被序列化的内容
    data.Add("A");
    data.Add("B");
    data.Add("C");
    return this.Xml(data, XmlRequestBehavior.AllowGet);
}

运行一下,看看实际返回结果吧!

上面的示例运行发挥的结果是这样:

<?xml version="1.0"?>
<ArrayOfString xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<string>A</string>
<string>B</string>
<string>C</string>
</ArrayOfString>

以下是完整的代码:
[C#] syntaxhighlighter_viewsource syntaxhighlighter_copycode
using System;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml.Serialization;

namespace Onexz.API.Models
{
    /// <summary>
    /// 扩展System.Web.Mvc XmlRequestBehavior
    /// 指定是否允许来自客户端的HTTP GET请求
    /// 熊仔其人/// </summary>
    public enum XmlRequestBehavior
    {
        /// <summary>
        /// HTTP GET requests from the client are allowed.
        /// 允许来自客户端的HTTP GET请求
        /// </summary>      
        AllowGet = 0,
        /// <summary>
        /// HTTP GET requests from the client are not allowed.
        /// 不允许来自客户端的HTTP GET请求
        /// </summary>
        DenyGet = 1,
    }

    /// <summary>
    /// 实现XmlResult继承ActionResult
    /// 扩展MVC的ActionResult支持返回XML格式结果
    /// 熊仔其人/// </summary>
    public class XmlResult : ActionResult
    {
        /// <summary>
        /// Initializes a new instance of the System.Web.Mvc.XmlResult class
        /// 初始化
        /// </summary>         
        public XmlResult() { }
        /// <summary>
        /// Encoding
        /// 编码格式
        /// </summary>
        public Encoding ContentEncoding { get; set; }
        /// <summary>
        /// Gets or sets the type of the content.
        /// 获取或设置返回内容的类型
        /// </summary>
        public string ContentType { get; set; }
        /// <summary>
        /// Gets or sets the data
        /// 获取或设置内容
        /// </summary>
        public object Data { get; set; }
        /// <summary>
        /// Gets or sets a value that indicates whether HTTP GET requests from the client
        /// 获取或设置一个值,指示是否HTTP GET请求从客户端
        /// </summary>
        public XmlRequestBehavior XmlRequestBehavior { get; set; }
        /// <summary>
        /// Enables processing of the result of an action method by a custom type that
        /// 处理结果
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null) { throw new ArgumentNullException("context"); }
            HttpRequestBase request = context.HttpContext.Request;
            if (XmlRequestBehavior == XmlRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("XmlRequest_GetNotAllowed");
            }
            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = !string.IsNullOrEmpty(this.ContentType) ? this.ContentType : "application/xml";
            if (this.ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }
            if (Data != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    XmlSerializer xs = new XmlSerializer(Data.GetType());
                    xs.Serialize(ms, Data); // 把数据序列化到内存流中                     
                    ms.Position = 0;
                    using (StreamReader sr = new StreamReader(ms))
                    {
                        context.HttpContext.Response.Output.Write(sr.ReadToEnd()); // 输出流对象 
                    }
                }
            }
        }
    }

    /// <summary>
    /// 扩展System.Mvc.Controller
    /// 熊仔其人/// </summary>
    public static class ControllerExtension
    {
        public static XmlResult Xml(this Controller request, object obj) { return Xml(obj, null, null, XmlRequestBehavior.DenyGet); }
        public static XmlResult Xml(this Controller request, object obj, XmlRequestBehavior behavior) { return Xml(obj, null, null, behavior); }
        public static XmlResult Xml(this Controller request, object obj, Encoding contentEncoding, XmlRequestBehavior behavior) { return Xml(obj, null, contentEncoding, behavior); }
        public static XmlResult Xml(this Controller request, object obj, string contentType, Encoding contentEncoding, XmlRequestBehavior behavior) { return Xml(obj, contentType, contentEncoding, behavior); }

        internal static XmlResult Xml(object data, string contentType, Encoding contentEncoding, XmlRequestBehavior behavior) { return new XmlResult() { ContentEncoding = contentEncoding, ContentType = contentType, Data = data, XmlRequestBehavior = behavior }; }
    }

}




分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|cqutlab ( 渝ICP备15004556号

GMT+8, 2024-12-22 10:05 , Processed in 0.178183 second(s), 31 queries .

Powered by Discuz! X3.1

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表