大家好,我是大成子,今天写一遍MVC控制器常见的返回的类型,总结一下过往的知识。
IActionResult
IActionResult就不多说了,它是所有Result的父类。下面说说几种常见的。
ViewResult
用于输出视图内容:
![](https://upload-images.jianshu.io/upload_images/13808716-f456df7debc14df3.png?imageMogr2/auto-orient/strip|imageView2/2/w/516/format/webp)
ContentResult
输出简单文本内容:
![](https://upload-images.jianshu.io/upload_images/13808716-34b6d55f99985504.png?imageMogr2/auto-orient/strip|imageView2/2/w/616/format/webp)
![](https://upload-images.jianshu.io/upload_images/13808716-2cd0b9c1e87bf143.png?imageMogr2/auto-orient/strip|imageView2/2/w/497/format/webp)
JsonResult
输出json字符串
![](https://upload-images.jianshu.io/upload_images/13808716-03121b94be816382.png?imageMogr2/auto-orient/strip|imageView2/2/w/693/format/webp)
跳转控制之重定向
Redirect:重定向页面跳转
![](https://upload-images.jianshu.io/upload_images/13808716-46323f87b0771682.png?imageMogr2/auto-orient/strip|imageView2/2/w/530/format/webp)
RedirectToAction:跳转到指定的action(可以是非本控制器)
![](https://upload-images.jianshu.io/upload_images/13808716-a336b7cc69bf0cae.png?imageMogr2/auto-orient/strip|imageView2/2/w/642/format/webp)
RedirectToRoute:使用指定的路由值跳转到指定的路由
![](https://upload-images.jianshu.io/upload_images/13808716-631e2b0f7b912f91.png?imageMogr2/auto-orient/strip|imageView2/2/w/778/format/webp)
文件输出
按指定的文件路径来输出文件:
注意:用此方法,没有涉及到文件流,不需要读取硬盘上的文件,所以直接使用虚拟路径,即相对路径
![](https://upload-images.jianshu.io/upload_images/13808716-e2fe36d89433d06e.png?imageMogr2/auto-orient/strip|imageView2/2/w/846/format/webp)
测试结果如下:
![](https://upload-images.jianshu.io/upload_images/13808716-0b00b1c30ef017be.png?imageMogr2/auto-orient/strip|imageView2/2/w/1200/format/webp)
使用字节数组输出文件:
![](https://upload-images.jianshu.io/upload_images/13808716-ea501bb4e9f4df9e.png?imageMogr2/auto-orient/strip|imageView2/2/w/940/format/webp)
测试如下:
![](https://upload-images.jianshu.io/upload_images/13808716-2d77dfd2f829de2c.png?imageMogr2/auto-orient/strip|imageView2/2/w/610/format/webp)
此为在线浏览方式,如若需要下载的方式,则在返回方法加上第三个参数,下载文件的命名:
![](https://upload-images.jianshu.io/upload_images/13808716-a6c260d51fb193cf.png?imageMogr2/auto-orient/strip|imageView2/2/w/979/format/webp)
![](https://upload-images.jianshu.io/upload_images/13808716-e8cb9ad3fc691ced.png?imageMogr2/auto-orient/strip|imageView2/2/w/1116/format/webp)
使用流方式输出文件:
![](https://upload-images.jianshu.io/upload_images/13808716-2800bf54ae7aef8f.png?imageMogr2/auto-orient/strip|imageView2/2/w/1020/format/webp)
总结:
1.本篇文章示例了MVC/API中返回的比较常见的几种类型,但不管是ViewResult还是ContentResult他们所有的类型的基类都是IActionResult,在写的时候可以不必写出具体的返回类型,直接写IActionResult。
2.也可以写平常我们所见的int,string,或者void亦或者其他类型
3.重定向。
Redirect(页面路径)
RedirectToAction(重定向到指定的控制器、动作方法)
RedirectToRoute(使用指定的路由值跳转)
4.重点是最后文件上传下载中的下载知识点,也就是文件资源的输出。
(1)直接使用项目中的路径资源,通过路径读取文件,输出文件。注意:需要使用虚拟(相对)路径。
(2)使用字节数组,输出文件资源。需要使用物理(绝对)路径。
(3)使用流,输出文件资源。需要使用物理(绝对路径)。
微信公众号:dotNET学习天地
好了,今天的学习就到这里结束了,有需要交流的请联系小编,共同学习进步。关于文件资源上传的,我们以后的学习再讲解。MVC和API原理差不多,返回类型也差不多,所以上述讲解的MVC中的全部内容在API中也同样适用。
代码地址:https://github.com/huguangcheng/_NET-Core_Study/tree/master/FileUpAndDown