MVC学习二:MVC Action Result 返回类型扩展

ActionResult是控制器方法执行后返回的结果类型,控制器方法可以返回一个直接或间接从ActionResult抽象类继承的类型,如果返回的是非ActionResult类型,控制器将会将结果转换为一个ContentResult类型。默认的ControllerActionInvoker调用ActionResult.ExecuteResult方法生成应答结果。

    MVC中实现的默认ActionResult如下:

ActionResult

1、ContentResult: 返回简单的纯文本内容,可通过ContentType属性指定应答文档类型,通过ContentEncoding属性指定应答文档的字符编码。可通过Controller类中的Content方法便捷地返回ContentResult对象。如果控制器方法返回非ActionResult对象,MVC将简单地以返回对象的ToString()内容为基础产生一个ContentResult对象。
2、EmptyResult: 返回一个空的结果。如果控制器方法返回一个null,MVC将其转换成EmptyResult对象。
3、RedirectResult: 表示一个连接跳转,相当于ASP.NET中的Response.Redirect方法。对应的Controller方法为Redirect。
4、RedirectToRouteResult:同样表示一个调转,MVC会根据我们指定的路由名称或路由信息(RouteValueDictionary)来生成Url地址,然后调用Response.Redirect跳转。对应的Controller方法为RedirectToAction和RedirectToRoute。
5、ViewResult: 表示一个视图结果,它根据视图模板产生应答内容。对应Controller方法为View。
6、PartialViewResult: 表示一个部分视图结果,与ViewResult本质上一致,只是部分视图不支持母版,对应于ASP.NET,ViewResult相当于一个Page,而PartialViewResult则相当于一个UserControl。它对应的Controller方法为PartialView。
7、HttpUnauthorizedResult: 表示一个未经授权访问的错误。MVC会向客户端发送一个401的应答状态。如果在web.config中开启了表单验证(authentication mode="Forms"),则401状态会将Url转向指定的loginUrl链接。
8、JavaScriptResult: 本质上是一个文本内容,只是将Response.ContentType设置为 application/x-javascript,此结果应该和MicrosoftMvcAjax.js脚本配合使用,客户端接收到Ajax应答后,将判断Response.ContentType的值,如果是application/x-javascript,则直接eval执行返回的应答内容。此结果类型对应的Controller方法为JavaScript。
9、JsonResult: 表示一个JSON结果。MVC将Response.ContentType设置为application/json,并通过JavaScriptSerializer类将指定对象序列化为Json表示方式。需要注意,默认情况下,MVC不允许GET请求返回JSON结果,要解除此限制,在生成JsonResult对象时,将其JsonRequestBehavior属性设置为JsonRequestBehavior.AllowGet。此结果对应的Controller方法为Json。
10、FilePathResult、FileContentResult、FileStreamResult: 这三个类继承于FileResult,表示一个文件内容,三者的区别在于,FilePath通过路径传送文件到客户端,FileContent通过二进制数据的方式,而FileStream是通过Stream的方式来传送。Controller为这三个文件结果类型提供了一个名为File的重载方法。

        通过直接或间接地从ActionResult继承,可实现自定义的结果类型,下例将实现一个XmlResult类型,用于返回XML应答内容:

1、创建一个空的MVC项目

2、实现XmlResult类

显示行号复制代码 XmlResult
  1. public class XmlResult : ActionResult
    
  2.  {
    
  3.     public XmlResult(Object data)
    
  4.     {
    
  5.         this.Data = data;
    
  6.     }
    
  7.     public Object Data
    
  8.     {
    
  9.         get;
    
  10.         set;
    
  11.     }
    
  12.     public override void ExecuteResult(ControllerContext context)
    
  13.     {
    
  14.         if (Data == null)
    
  15.         {
    
  16.             new EmptyResult().ExecuteResult(context);
    
  17.             return;
    
  18.         }
    
  19.         context.HttpContext.Response.ContentType = "application/xml";
    
  20.         using (MemoryStream ms = new MemoryStream())
    
  21.         {
    
  22.             XmlSerializer xs = new XmlSerializer(Data.GetType());
    
  23.             xs.Serialize(ms, Data);
    
  24.             ms.Position = 0;
    
  25.             using (StreamReader sr = new StreamReader(ms))
    
  26.             {
    
  27.                 context.HttpContext.Response.Output.Write(sr.ReadToEnd());
    
  28.             }
    
  29.         }
    
  30.     }
    
  31. }
    
  32.  

3、创建一个HomeController,实现Index方法

public ActionResult Index()
{
    return new XmlResult(new Product()
    {
        ID = "000001",
        Name = "测a试?",
        Description = ""
    });
}
 
    /// <summary>
    /// This code was found here:
    /// http://blogs.msdn.com/b/miah/archive/2008/11/13/extending-mvc-returning-an-image-from-a-controller-action.aspx
    /// </summary>
    public class ImageResult : ActionResult
    {
        public ImageResult(Stream imageStream, string contentType)
        {
            if (imageStream == null)
                throw new ArgumentNullException("imageStream");
            if (contentType == null)
                throw new ArgumentNullException("contentType");
 
            this.ImageStream = imageStream;
            this.ContentType = contentType;
        }
 
        public Stream ImageStream { get; private set; }
        public string ContentType { get; private set; }
 
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
 
            HttpResponseBase response = context.HttpContext.Response;
 
            response.ContentType = this.ContentType;
        
            byte[] buffer = new byte[4096];
            while (true)
            {
                int read = this.ImageStream.Read(buffer, 0, buffer.Length);
                if (read == 0)
                    break;
 
                response.OutputStream.Write(buffer, 0, read);
            }
 
            response.End();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值