【.NET Core】ActionResult及其常用派生类

news/2024/5/19 21:08:28 标签: .netcore, microsoft, MVC, Result

文章目录

Result_1">ActionResult

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

ActionResult默认实现 IActionResult

public abstract class ActionResult : Microsoft.AspNetCore.Mvc.IActionResult

派生与继承

ActionResult继承与Object,mvc的返回result基本都继承于ActionResult

派生:

/*
	返回文件内容。FilePath通过路径传送文件到客户端,FileContent通过二进制数据的方式,而FileStream是通过Stream的方式来传送。Controller为这三个文件结果类型提供了一个名为File的重载方法。
*/
Microsoft.AspNetCore.Mvc.ContentResult
```csharp
/*
	返回文件内容。FilePath通过路径传送文件到客户端,FileContent通过二进制数据的方式,而FileStream是通过Stream的方式来传送。Controller为这三个文件结果类型提供了一个名为File的重载方法。
*/
Microsoft.AspNetCore.Mvc.ChallengeResult
/*
	返回简单的纯文本内容,可通过ContentType属性指定应答文档类型,通过ContentEncoding属性指定应答文档的字符编码。可通过Controller类中的Content方法便捷地返回ContentResult对象。如果控制器方法返回非ActionResult对象,MVC将简单地以返回对象的ToString()内容为基础产生一个ContentResult对象。
*/
Microsoft.AspNetCore.Mvc.ContentResult
/*
返回一个空的结果。如果控制器方法返回一个null,MVC将其转换成EmptyResult对象。
*/
Microsoft.AspNetCore.Mvc.EmptyResult
/*FilePathResult、FileContentResult、FileStreamResult这三个类继承于FileResult,表示一个文件内容,三者区别在于,FilePath 通过路径传送文件到客户端,FileContent 通过二进制数据的方式,而FileStream 是通过Stream(流)的方式来传送。Controller为这三个文件结果类型提供了一个名为File的重载方法。

FilePathResult: 直接将一个文件发送给客户端

FileContentResult: 返回byte字节给客户端(比如图片)

FileStreamResult: 返回流*/
Microsoft.AspNetCore.Mvc.FileResult
Microsoft.AspNetCore.Mvc.ForbidResult
/*
返回Json格式数据。 MVC将Response.ContentType设置为application/json,并通过JavaScriptSerializer类将指定对象序列化为Json表示方式。需要注意,默认情况下,MVC不允许GET请求返回JSON结果,要解除此限制,在生成JsonResult对象时,将其JsonRequestBehavior属性设置为JsonRequestBehavior.AllowGet。此结果对应的Controller方法为Json。
*/
Microsoft.AspNetCore.Mvc.JsonResult
Microsoft.AspNetCore.Mvc.LocalRedirectResult
Microsoft.AspNetCore.Mvc.ObjectResult
/*接收分部视图引擎的响应*/
Microsoft.AspNetCore.Mvc.PartialViewResult
Microsoft.AspNetCore.Mvc.RazorPages.PageResult
/*表示一个连接跳转,相当于ASP.NET中的Response.Redirect方法。对应的Controller方法为Redirect。*/
Microsoft.AspNetCore.Mvc.RedirectResult
Microsoft.AspNetCore.Mvc.RedirectToActionResult
Microsoft.AspNetCore.Mvc.RedirectToPageResult
/*同样表示一个跳转,MVC会根据我们指定的路由名称或路由信息(RouteValueDictionary)来生成Url地址,然后调用Response.Redirect跳转。对应的Controller方法为RedirectToAction和RedirectToRoute.*/
Microsoft.AspNetCore.Mvc.RedirectToRouteResult
Microsoft.AspNetCore.Mvc.SignInResult
Microsoft.AspNetCore.Mvc.SignOutResult
Microsoft.AspNetCore.Mvc.StatusCodeResult
Microsoft.AspNetCore.Mvc.ViewComponentResult
/*接收视图引擎的响应*/
Microsoft.AspNetCore.Mvc.ViewResult

Result_65">Result的封装

除了通过new对象返回结果外,还可以使用封装后的方法;

在这里插入图片描述
示例:

        public IActionResult Result1()//实例化对象
        {
            JsonResult result = new JsonResult(new { name = "kxy1" });
            return result;
        }
        public IActionResult Result2()//封装方法
        {
            return Json(new { name = "kxy2" });
        }

Result_83">扩展ActionResult

下例将实现一个XmlResult类型,用于返回XML应答内容:

    public class XmlResult : ActionResult
     {
        public XmlResult(Object data)
        {
            this.Data = data;
        }
 
        public Object Data
        {
            get;
            set;
        }
 
        public override void ExecuteResult(ControllerContext context)
        {
            if (Data == null)
            {
                new EmptyResult().ExecuteResult(context);
                return;
            }
 
            context.HttpContext.Response.ContentType = "application/xml";
            using (MemoryStream ms = new MemoryStream())
            {
                XmlSerializer xs = new XmlSerializer(Data.GetType());
                xs.Serialize(ms, Data);
                ms.Position = 0;
                using (StreamReader sr = new StreamReader(ms))
                {
                    context.HttpContext.Response.Output.Write(sr.ReadToEnd());
                }
            }
        }
    } 

MVCActionResult12_123">.NET MVC下ActionResult(12种)的简单应用

注:AspNetCore.Mvc不一定兼容

using StudyMVC4.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;

namespace StudyMVC4.Controllers
{
    public class HomeController : Controller
    {
       
        public ActionResult Index() {
            return View();
        }

        /// <summary>
        /// ContentResult用法(返回文本)
        /// http://localhost:30735/home/ContentResultDemo
        /// </summary>
        /// <returns>返回文本</returns>
        public ActionResult ContentResultDemo(){
            string str = "ContentResultDemo!";
            return Content(str);
        }

        /// <summary>
        /// EmptyResult的用法(返回空对象)
        /// http://localhost:30735/home/EmptyResultDemo
        /// </summary>
        /// <returns>返回一个空对象</returns>
        public ActionResult EmptyResultDemo (){
            return new EmptyResult();
        }

        /// <summary>
        /// FileContentResult的用法(返回图片)
        /// http://localhost:30735/home/FileContentResultDemo
        /// </summary>
        /// <returns>显示一个文件内容</returns>
        public ActionResult FileContentResultDemo() {
            FileStream fs = new FileStream(Server.MapPath(@"/Images/001.jpg"), FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[Convert.ToInt32(fs.Length)];
            fs.Read(buffer, 0, Convert.ToInt32(fs.Length));
            string contentType = "image/jpeg";
            return File(buffer, contentType);
        }
      
        /// <summary>
        /// FilePathResult的用法(返回图片)
        /// http://localhost:30735/home/FilePathResultDemo/002
        /// </summary>
        /// <param name="id">图片id</param>
        /// <returns>直接将返回一个文件对象</returns>
        public FilePathResult FilePathResultDemo(string id)
        {
            string path = Server.MapPath(@"/Images/"+id +".jpg");
            //定义内容类型(图片)
            string contentType = "image/jpeg";
            //FilePathResult直接返回file对象
            return File(path, contentType);
        }

        /// <summary>
        /// FileStreamResult的用法(返回图片)
        /// http://localhost:30735/home/FileStreamResultDemo
        /// </summary>
        /// <returns>返回文件流(图片)</returns>
        public ActionResult FileStreamResultDemo()
        {
            FileStream fs = new FileStream(Server.MapPath(@"/Images/001.jpg"), FileMode.Open, FileAccess.Read);
            string contentType = "image/jpeg";
            return File(fs, contentType);
        }

        /// <summary>
        /// HttpUnauthorizedResult 的用法(抛出401错误)
        /// http://localhost:30735/home/HttpUnauthorizedResult
        /// </summary>
        /// <returns></returns>
        public ActionResult HttpUnauthorizedResultDemo()
        {
            return new HttpUnauthorizedResult();
        }

        /// <summary>
        /// HttpStatusCodeResult的方法(返回错误状态信息)
        ///  http://localhost:30735/home/HttpStatusCodeResult
        /// </summary>
        /// <returns></returns>
        public ActionResult HttpStatusCodeResultDemo() {
            return new HttpStatusCodeResult(500, "System Error");
        }

        /// <summary>
        /// HttpNotFoundResult的使用方法
        /// http://localhost:30735/home/HttpNotFoundResultDemo
        /// </summary>
        /// <returns></returns>
        public ActionResult HttpNotFoundResultDemo() {
            return new HttpNotFoundResult("not found action");
        }

       /// <summary>
       /// JavaScriptResult 的用法(返回脚本文件)
        /// http://localhost:30735/home/JavaScriptResultDemo
       /// </summary>
       /// <returns>返回脚本内容</returns>
        public ActionResult JavaScriptResultDemo()
        {
            return JavaScript(@"<script>alert('Test JavaScriptResultDemo!')</script>");
        }

        /// <summary>
        /// JsonResult的用法(返回一个json对象)
        /// http://localhost:30735/home/JsonResultDemo
        /// </summary>
        /// <returns>返回一个json对象</returns>
        public ActionResult JsonResultDemo()
        {
            var tempObj = new { Controller = "HomeController", Action = "JsonResultDemo" };
            return Json(tempObj);
        }

        /// <summary>
        /// RedirectResult的用法(跳转url地址)
        /// http://localhost:30735/home/RedirectResultDemo
        /// </summary>
        /// <returns></returns>
        public ActionResult RedirectResultDemo()
        {
            return Redirect(@"http://wwww.baidu.com");
        }

        /// <summary>
        /// RedirectToRouteResult的用法(跳转的action名称)
        /// http://localhost:30735/home/RedirectToRouteResultDemo
        /// </summary>
        /// <returns></returns>
        public ActionResult RedirectToRouteResultDemo()
        {
            return RedirectToAction(@"FileStreamResultDemo");
        }

        /// <summary>
        /// PartialViewResult的用法(返回部分视图)
        /// http://localhost:30735/home/PartialViewResultDemo
        /// </summary>
        /// <returns></returns>
        public PartialViewResult PartialViewResultDemo()
        {
            return PartialView();
        }

       /// <summary>
       /// ViewResult的用法(返回视图)
        ///  http://localhost:30735/home/ViewResultDemo
       /// </summary>
       /// <returns></returns>
        public ActionResult ViewResultDemo()
        {
            //如果没有传入View名称, 默认寻找与Action名称相同的View页面.
            return View();
        }
    }
}

来源

ActionResult 详解
ActionResult
MVC中几种常用ActionResult


http://www.niftyadmin.cn/n/130588.html

相关文章

【微信小程序】-- 生命周期(二十八)

&#x1f48c; 所属专栏&#xff1a;【微信小程序开发教程】 &#x1f600; 作  者&#xff1a;我是夜阑的狗&#x1f436; &#x1f680; 个人简介&#xff1a;一个正在努力学技术的CV工程师&#xff0c;专注基础和实战分享 &#xff0c;欢迎咨询&#xff01; &…

【数据结构】二叉搜索树

1、什么是二叉搜索树二叉搜索树又称为二叉排序树&#xff0c;二叉也就说明它跟二叉树一样最多只能有两个度&#xff0c;它可以是棵空树&#xff0c;也可以不是棵空树&#xff0c;当它不是棵空树的时候需要具备以下的性质&#xff1a;若它的左树不为空&#xff0c;那么它的左树上…

字典树及其实现

一、什么是字典树 字典树&#xff08;Trie树、前缀树&#xff09;是一种用于快速检索的多叉树结构。字典树把字符串看成字符序列&#xff0c;根据字符串中字符序列的先后顺序构造从上到下的树结构&#xff0c;树结构中的每一条边都对应着一个字符。字典树上存储的字符串被视为…

mybatis 数据库查询的一些点

1. 接受到前端输入的一批ID &#xff0c;然后去查询这批ID 的记录 ArrayList<String> getScopeId_FId(Param(value "textValue") String textValue); select b.FId from ( select arrayJoin(splitByChar(,, ${textValue} )) as FId ) a join datahouse.bas…

MATLAB学习笔记1

MATLAB学习笔记1 - 向量和矩阵 Matlab的数组可以是行向量&#xff0c;列向量&#xff0c;矩阵形式等 1.利用[ ]创建数组 例&#xff1a;包含7和9的一个数组&#xff0c;使用空格或&#xff0c;为行 x [7 9]//x是一个1*2的矩阵 y[7,9]//y是一个1*2的矩阵例&#xff1a;包含7和…

SQL注入——布尔盲注

目录 一&#xff0c;盲注的概念 二&#xff0c;盲注分类 三&#xff0c;注入方法的选择 四&#xff0c;关键函数 五&#xff0c;实例 一&#xff0c;盲注的概念 页面没有报错回显&#xff0c;不知道数据库具体返回值的情况下&#xff0c;对数据库中的内容进行猜解&#x…

linux和centos读写日期到文件并对日期进行比较

#!/bin/bash adate -d "${a}" %s #必须用数字 %s是取时间戳秒数 ddate -d "${c}" %s echo m$(($a - $d)) #必须2个小括号 a1date %s echo $a1 sleep 2 b1date %s echo $(($a1 - $b1)) #必须2个小括号 if [ $a1 -eq $b1 ];then #必须有空格 echo "…

Java数据类型和转换

Scanner相关操作&#xff1a;参考文章 字符串数组转化为int数组 String s in.nextLine();//获取字符串中的每一个数字.字符串转数组String[] strArr s.split(",");​//创建一个int类型的数组.int [] numberArr new int[strArr.length];​//把strArr中的数据进行…