博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
MVC学习二:MVC Action Result 返回类型扩展
阅读量:2386 次
发布时间:2019-05-10

本文共 3816 字,大约阅读时间需要 12 分钟。

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

    MVC中实现的默认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.  
  8. public Object Data
  9. {
  10. get;
  11. set;
  12. }
  13.  
  14. public override void ExecuteResult(ControllerContext context)
  15. {
  16. if (Data == null)
  17. {
  18. new EmptyResult().ExecuteResult(context);
  19. return;
  20. }
  21. context.HttpContext.Response.ContentType = "application/xml";
  22. using (MemoryStream ms = new MemoryStream())
  23. {
  24. XmlSerializer xs = new XmlSerializer(Data.GetType());
  25. xs.Serialize(ms, Data);
  26. ms.Position = 0;
  27. using (StreamReader sr = new StreamReader(ms))
  28. {
  29. context.HttpContext.Response.Output.Write(sr.ReadToEnd());
  30. }
  31. }
  32. }
  33. }
  34.  

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

public ActionResult Index()
{
return new XmlResult(new Product()
{
ID = "000001",
Name = "测a试?",
Description = ""
});
}
 
    ///     /// This code was found here:    ///     ///     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();        }    }

转载地址:http://kljab.baihongyu.com/

你可能感兴趣的文章
Php Endangers - Remote Code Execution
查看>>
变量的变量,PHP和你
查看>>
PROC系列之四---/proc/loadavg
查看>>
某大型网站的内核TCP/ip优化脚本
查看>>
Defeating SSL using SSLStrip (Marlinspike Blackhat)
查看>>
大型网站数据库架构
查看>>
rdp 安全策略
查看>>
Threat Intelligence Quotient Test
查看>>
Cisco路由器上防止DDOS的一些建议
查看>>
系统安全防护之UNIX下入侵检测方法
查看>>
域控渗透技巧
查看>>
Minion security project and 分布式nmap
查看>>
防火墙相关
查看>>
网络性能测试工具Iperf上手指南
查看>>
opensecuritytraining video
查看>>
collective intelligence framework
查看>>
2015年关注的技术书籍
查看>>
windows 2003 server 记录远程桌面的连接登录日志和修改3389连接端口方法
查看>>
samhain:比较变态的入侵检测系统
查看>>
Linux psacct文档
查看>>