Backend - HTTP请求的常用返回类型(asp .net core MVC)

目录

[一、ViewResult 类型](#一、ViewResult 类型)

[1. 写法](#1. 写法)

[2. 用途](#2. 用途)

[二、RedirectToActionResult 类型](#二、RedirectToActionResult 类型)

[1. 写法](#1. 写法)

[2. 用途](#2. 用途)

[三、ContentResult 类型](#三、ContentResult 类型)

[1. 写法](#1. 写法)

[2. 用途](#2. 用途)

[四、OkObjectResult 类型](#四、OkObjectResult 类型)

[1. 写法](#1. 写法)

[2. 用途](#2. 用途)

五、JsonResult

[1. 写法](#1. 写法)

[2. 用途](#2. 用途)


以下介绍几种 IActionResult 的类型

一、ViewResult 类型

1. 写法

cs 复制代码
// AccountController类下的Login方法
public IActionResult Login()
{
    var model = new LoginViewModel();
    return View(model); // 对应Views/Account/Login.cshtml
}

2. 用途

返回 Razor 页面,一般在 MVC 控制器中使用。

常用于登录页、主页、表单页等需要视图渲染的场景。

二、RedirectToActionResult 类型

1. 写法

cs 复制代码
public IActionResult Logout()
{
    HttpContext.SignOutAsync();
    return RedirectToAction("Login", "Account");
}

2. 用途

服务器端重定向到另一个 Action。

常用于登录后跳转、提交表单成功后重定向到主页、退出登录后返回登录页。

三、ContentResult 类型

1. 写法

cs 复制代码
public IActionResult ForceLogout()
{
    return Content("<script>window.top.location.href='/Account/Login';</script>", "text/html");
}

2. 用途

直接返回一段字符串作为 HTTP 响应。

常用于用户登录超时、将当前页面跳出 iframe 、让顶层窗口跳转(而不是标签页内部)。

四、OkObjectResult 类型

1. 写法

cs 复制代码
[HttpGet]
public IActionResult GetMenuTree()
{
    var tree = _menuService.GetTree();
    return Ok(tree);
}

在tree传入前端时,会自动处理成JSON格式

javascript 复制代码
{
  "id": 1,
  "name": "系统管理",
  "children": [...]
}

2. 用途

返回 HTTP 200 状态的 JSON 数据。

常用于Web API 推荐写法、以及Layui、Vue、React 前端请求数据。

五、JsonResult

1. 写法

cs 复制代码
public IActionResult GetUserPermissions()
{
    var rp = _userService.GetRolePermission(User.Identity.Name);
    return Json(new { menus = new List<int> { rp.MenuId }, buttons = rp.ButtonCodes });
}

在传入前端时,会处理成JSON格式

javascript 复制代码
{
  "menus": [1, 2, 3],
  "buttons": ["Add", "Edit", "Delete"]
}

2. 用途

直接返回 JSON 格式内容。

Ok()很像,Ok(object) 更符合 REST 风格,Json(object) 是 MVC 传统写法。

相关推荐
暖馒7 小时前
Modbus应用层协议的深度剖析
网络·网络协议·c#·wpf·智能硬件
开源技术8 小时前
DNS详解——域名是如何解析的
http
刘欣的博客10 小时前
C# CS架构程序发版升级的走数据库方案
c#·单文件升级自己的方式
Yorlen_Zhang12 小时前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#
不绝19112 小时前
C#进阶:预处理指令/反射,Gettype,Typeof/关键类
开发语言·c#
大鹏说大话12 小时前
告别 MSBuild 脚本混乱:用 C# 和 Nuke 构建清晰、可维护的现代化构建系统
开发语言·c#
czhc114007566313 小时前
通信 28
c#
三水不滴15 小时前
有 HTTP 了为什么还要有 RPC?
经验分享·笔记·网络协议·计算机网络·http·rpc
bugcome_com17 小时前
C# 程序结构详解:从 Hello World 开始
c#
唐梓航-求职中18 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#