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 传统写法。

相关推荐
谢尔登1 小时前
HTTPS 究竟比 HTTP 好在哪?
http·https·ssl
yue0085 小时前
C# 更改窗体样式
开发语言·c#
Charles_go6 小时前
C#中级1、元祖和值元组有什么区别
c#
C#程序员一枚9 小时前
导出百万量数据到Excel表
c#·excel
k***38810 小时前
Node.js HTTP模块详解:创建服务器、响应请求与客户端请求
服务器·http·node.js
攻城狮CSU11 小时前
C# 异步方法
开发语言·前端·c#
ekkcole11 小时前
java word转pdf工具类,兼容linux和windows服务器
开发语言·pdf·c#
yangshuquan12 小时前
C# 委托和事件的3点区别,你知道几个?
c#·委托·事件·编程技巧
i***486112 小时前
Nginx中$http_host、$host、$proxy_host的区别
运维·nginx·http