在ASP.NET MVC的controller中大部分方法返回的都是ActionResult,更确切的是ViewResult。它返回了一个View,一般情况下是一个HTML页面。但是在某些情况下我们可能并不需要返回一个View,我们可能需要的是一个字符串,一个json或xml格式的文本,一个图片。
ActionResult是一个抽象类,我们平时比较常用的ViewResult是它的派生类,所以我们也可以写一个StringResult、XmlResult、ImageResult来实现上面提到的需求。由于返回字符串可以有更简单的方法,直接将需要返回字符串的方法的返回值设置成string型就可以了,JsonResult在ASP.NET MVC中已经有提供。所以下面只演示XmlResult和ImageResult。
ASP.NET MVC项目是开源的(可以在http://www.codeplex.com/aspnet下载源代码),所以我们可以参考其中ViewResult和JsonResult的代码进行改写。主要的思路是设置返回数据流HTTP Header中的Content-Type,然后将要返回的内容写入Response中。
先演示XmlResult
XmlResult的代码:
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
}
在controller中调用它
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
}
显示出来的结果
![让ASP.NET MVC页面返回不同类型的内容](http://img.e-com-net.com/image/product/ee2d79c2bc8242c3a216efc009d4b731.jpg)
下面演示的是ImageResult
ImageResult的代码
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
}
在controller中调用
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
}
结果图
![让ASP.NET MVC页面返回不同类型的内容](http://img.e-com-net.com/image/product/cf18b1b98d344f4e9fb46eb4a0b43c4b.jpg)
这个比较多用在向客户端传送验证码图片时。
转载地址:http://www.cnblogs.com/snowdreams/archive/2008/11/15/let-aspnet-mvc-view-return-different-type-content.html