1 public class XmlResult:ActionResult
2 {
3 // 可被序列化的内容
4 object Data { get; set; }
5
6 // Data的类型
7 Type DataType { get; set; }
8
9 // 构造器
10 public XmlResult(object data,Type type)
11 {
12 Data = data;
13 DataType = type;
14 }
15
16 // 主要是重写这个方法
17 public override void ExecuteResult(ControllerContext context)
18 {
19 if (context == null)
20 {
21 throw new ArgumentNullException("context");
22 }
23
24 HttpResponseBase response = context.HttpContext.Response;
25
26 // 设置 HTTP Header 的 ContentType
27 response.ContentType = "text/xml";
28
29 if (Data != null)
30 {
31 // 序列化 Data 并写入 Response
32 XmlSerializer serializer = new XmlSerializer(DataType);
33 MemoryStream ms = new MemoryStream();
34 serializer.Serialize(ms,Data);
35 response.Write(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
36 }
37 }
38 }
1 public ActionResult Xml()
2 {
3 // 创建一个DemoModal对象,No属性为1,Title属性为Test
4 DemoModal dm = new DemoModal() { No = 1, Title = "Test" };
5
6 // 序列化为XML格式显示
7 XmlResult xResult = new XmlResult(dm, dm.GetType());
8 return xResult;
9 }
1 public class ImageResult:ActionResult
2 {
3 // 图片
4 public Image imageData;
5
6 // 构造器
7 public ImageResult(Image image)
8 {
9 imageData = image;
10 }
11
12 // 主要需要重写的方法
13 public override void ExecuteResult(ControllerContext context)
14 {
15 if (context == null)
16 {
17 throw new ArgumentNullException("context");
18 }
19
20 HttpResponseBase response = context.HttpContext.Response;
21
22 // 设置 HTTP Header
23 response.ContentType = "image/jpeg";
24
25 // 将图片数据写入Response
26 imageData.Save(context.HttpContext.Response.OutputStream, ImageFormat.Jpeg);
27 }
28 }
1 public ActionResult Img()
2 {
3 // 获取博客园空间顶部的banner图片
4 WebRequest req = WebRequest.Create("http://space.cnblogs.com/images/a4/banner.jpg");
5 WebResponse res = req.GetResponse();
6 Stream resStream = res.GetResponseStream();
7 Image img = Image.FromStream(resStream);
8
9 // 输出给客户端
10 ImageResult r = new ImageResult(img);
11 return r;
12 }