.Net MVC 自定义Action类型,XmlAction,ImageAction等

MVC开发的时候,难免会用到XML格式数据,如果将XML数据当作字符串直接返回给前台,其实这不是真正意义上的xmL,你可以看到ContentType是text/html而非XML类型,这往往会造成前端架构无法解析的情况,例如Extjs。

错误实例:

public string GetXmlData()
{
  return "<ROOT><List><user><name></name><sex></sex></user></List></ROOT>";
}
//通过跟踪,会发现ContentType:text/html类型的

定义XmlAction:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Serialization;

namespace ElegantWM.WebUI
{
    public class XmlResult : ActionResult
    {
        // 可被序列化的内容
        object Data { get; set; }

        // Data的类型
        Type DataType { get; set; }

        // 构造器
        public XmlResult(string data)
        {
            Data = data;
        }
        public XmlResult(object data, Type type)
        {
            Data = data;
            DataType = type;
        }
        //静态调用
        public static XmlResult Xml(string data)
        {
            return new XmlResult(data);
        }
        // 主要是重写这个方法
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            // 设置 HTTP Header 的 ContentType
            response.ContentType = "text/xml";

            if (Data != null)
            {
                if (DataType == null)
                    response.Write(Data);
                else
                {
                    //序列化 Data 并写入 Response
                    XmlSerializer serializer = new XmlSerializer(DataType);
                    MemoryStream ms = new MemoryStream();
                    serializer.Serialize(ms, Data);
                    response.Write(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
                }
            }
        }
    }
}

使用:

[Description("获取列表")]
[Action]
[HttpGet]
public XmlResult Get()
{
return XmlResult.Xml("<ROOT><List><user><name></name><sex></sex></user></List></ROOT>");
}

这样你访问该服务,会在浏览器上打印出完整的xml架构,而非一串字符。

ImageResult同样类似:

public class ImageResult:ActionResult
    {
        // 图片
        public Image imageData;

        // 构造器
        public ImageResult(Image image)
        {
            imageData = image;
        }

        // 主要需要重写的方法
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            // 设置 HTTP Header
            response.ContentType = "image/jpeg";

            // 将图片数据写入Response
            imageData.Save(context.HttpContext.Response.OutputStream, ImageFormat.Jpeg);
        }
    }

其实关键点就是respone.ContentType,你可以以此扩展其他的Result类型。

原文地址:https://www.cnblogs.com/qidian10/p/3257426.html