Backend - HTTP请求的常用返回类型(asp .net core MVC)
目录
一、ViewResult 类型
1. 写法
2. 用途
二、RedirectToActionResult 类型
1. 写法
2. 用途
三、ContentResult 类型
1. 写法
2. 用途
四、OkObjectResult 类型
1. 写法
2. 用途
五、JsonResult
1. 写法
2. 用途
以下介绍几种 IActionResult 的类型
一、ViewResult 类型
1. 写法
// AccountController类下的Login方法
public IActionResult Login()
{var model = new LoginViewModel();return View(model); // 对应Views/Account/Login.cshtml
}
2. 用途
返回 Razor 页面,一般在 MVC 控制器中使用。
常用于登录页、主页、表单页等需要视图渲染的场景。
二、RedirectToActionResult 类型
1. 写法
public IActionResult Logout()
{HttpContext.SignOutAsync();return RedirectToAction("Login", "Account");
}
2. 用途
服务器端重定向到另一个 Action。
常用于登录后跳转、提交表单成功后重定向到主页、退出登录后返回登录页。
三、ContentResult 类型
1. 写法
public IActionResult ForceLogout()
{return Content("<script>window.top.location.href='/Account/Login';</script>", "text/html");
}
2. 用途
直接返回一段字符串作为 HTTP 响应。
常用于用户登录超时、将当前页面跳出 iframe 、让顶层窗口跳转(而不是标签页内部)。
四、OkObjectResult 类型
1. 写法
[HttpGet]
public IActionResult GetMenuTree()
{var tree = _menuService.GetTree();return Ok(tree);
}
在tree传入前端时,会自动处理成JSON格式
{"id": 1,"name": "系统管理","children": [...]
}
2. 用途
返回 HTTP 200 状态的 JSON 数据。
常用于Web API 推荐写法、以及Layui、Vue、React 前端请求数据。
五、JsonResult
1. 写法
public IActionResult GetUserPermissions()
{var rp = _userService.GetRolePermission(User.Identity.Name);return Json(new { menus = new List<int> { rp.MenuId }, buttons = rp.ButtonCodes });
}
在传入前端时,会处理成JSON格式
{"menus": [1, 2, 3],"buttons": ["Add", "Edit", "Delete"]
}
2. 用途
直接返回 JSON 格式内容。
与 Ok()很像,Ok(object) 更符合 REST 风格,Json(object) 是 MVC 传统写法。
