ControllerBase 类将对象转换为 JSON 格式并返回前端的方法

ControllerBase 类将对象转换为 JSON 格式并返回前端的方法

ASP.NET Core 框架中,ControllerBase 类提供了多种便捷的方法来将对象转换为 JSON 格式并返回给客户端。这些方法通常返回 IActionResult 或其子类(如 ObjectResult、JsonResult),框架会自动处理序列化过程。

基本都在Microsoft.AspNetCore.Mvc空间下

以下是几种常用的方法:

一、使用 Ok() 方法(最常用)

Ok() 方法返回一个状态码为 200 (OK) 的响应,并将传入的对象序列化为 JSON。这是 RESTful API 中最常见的返回成功数据的方式。

csharp 复制代码
[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
    var user = new { Id = id, Name = "张三" };
    // 自动序列化为 JSON,状态码 200
    return Ok(user); 
}
二、使用JsonResult() 方法

Json() 方法显式地返回一个 JsonResult。它允许你更明确地指示返回内容是 JSON 格式,并且可以指定 JSON 序列化设置(如缩进、日期格式等)或内容类型。

csharp 复制代码
[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
    var user = new { Id = id, Name = "张三" };
    // 显式返回 JsonResult
    return Json(user); 
}

// 如果需要自定义序列化设置
[HttpGet("details")]
public IActionResult GetDetails()
{
    var data = new { Message = "Hello" };
    return new JsonResult(data) 
    { 
        StatusCode = 200,
        SerializerSettings = new JsonSerializerOptions { WriteIndented = true } 
    };
}
三、使用 StatusCode() 配合对象

如果你需要返回非 200 的状态码(如 201 Created, 202 Accepted 等)同时返回 JSON 数据,可以使用 StatusCode 方法。

csharp 复制代码
[HttpPost]
public IActionResult CreateUser([FromBody] User user)
{
    // 保存用户逻辑...
    

    // 返回 201 Created 状态码,并将用户对象序列化为 JSON
    return StatusCode(201, user);

}
四、使用特定的结果辅助方法

ControllerBase 提供了一系列针对特定 HTTP 状态码的辅助方法,它们都会自动将对象序列化为 JSON:

CreatedAtAction / CreatedAtRoute‌: 返回 201 Created,常用于创建资源后返回新资源的 URI 和数据。

csharp 复制代码
return CreatedAtAction(nameof(GetUser), new { id = newUser.Id }, newUser);
BadRequest‌: 返回 400 Bad Request,通常用于验证失败时返回错误信息的 JSON。
csharp 复制代码
return BadRequest(new { error = "输入参数无效" });
NotFound‌: 返回 404 Not Found。
csharp 复制代码
return NotFound(new { message = "用户不存在" });
Unauthorized‌: 返回 401 Unauthorized。
Forbidden‌: 返回 403 Forbidden。
五、直接返回对象(配合 ApiController 特性)

如果你的控制器类添加了 ApiController 特性,你可以直接返回 POCO(普通 CLR 对象)或 Task,框架会自动将其包装为 ObjectResult 并序列化为 JSON。这虽然不是 ControllerBase 的直接方法,但是基于 ControllerBase 的现代开发最佳实践。

csharp 复制代码
[ApiController]
[Route("[controller]")]
public class UserController : ControllerBase
{
    [HttpGet("{id}")]
    public User GetUser(int id) // 直接返回对象,自动转为 JSON
    {
        return new User { Id = id, Name = "张三" };
    }
}
六、最佳实现方案
csharp 复制代码
	[ApiController]
	[Route("api/[controller]")]
	public class ApiControllerBase : ControllerBase
	{


		/// <summary>
		/// 用于返回成功·视图数据的通用方法
		/// </summary>
		/// <param name="message">消息</param>
		/// <param name="data">数据</param>
		/// <returns></returns>
		protected IActionResult SuccessResult(ResultType code = ResultType.Success, string message = "操作成功!", object? data = null, int count = 0)
		{

			return new JsonResult(new LayuiResponse(ResultType.Success, message, data, count));
		}

		/// <summary>
		/// 用于返回成功,视图无数据的通用方法
		/// </summary>
		/// <returns></returns>
		protected IActionResult SuccessResult()
		{
			return new JsonResult(new { code = 200, Message = "操作成功!" });
		}
		/// <summary>
		/// 用于返回失败·视图数据的通用方法
		/// </summary>
		/// <param name="message">消息</param>
		/// <param name="data">数据</param>
		/// <param name="count">总记录数</param>
		/// <returns></returns>
		protected IActionResult ErrorResult(string message, object? data = null, int count = 0)
		{
			return new JsonResult(new LayuiResponse(ResultType.Error, message, data, count));
		}

		/// <summary>
		/// 用于返回失败·无数据的通用方法
		/// </summary>
		/// <param name="message">消息</param>
		/// <param name="data">数据</param>
		/// <param name="count">总记录数</param>
		/// <returns></returns>
		protected IActionResult ErrorResult(string message = "操作失败!")
		{
			return new JsonResult(new { code = 400, Message = message });
		}


	}
相关推荐
凌风的跨境分享13 分钟前
Temu店群运维提效:定时策略自动化任务全场景实操指南
大数据·运维·前端·人工智能·架构·自动化
linux_cfan35 分钟前
videojs v10 源代码系列解读:06 · DOM 工具箱:事件、聚焦、Shadow DOM、定位
前端
尾善爱看海43 分钟前
Vue 面试进阶篇:Composition API、插槽、自定义指令……8 个章节 + 高频面试题全解析
前端·javascript·vue.js·面试·vue
SEO_juper1 小时前
外贸多语言站最隐蔽的流量杀手:hreflang 错了,谷歌把德语页推给美国人(附审计脚本)
开发语言·前端·python·seo·独立站·谷歌优化
亿元程序员1 小时前
为什么现在 AI 这么发达了,还要坚持手搓教程?
前端
三小河2 小时前
在 Codex 桌面端接入 DeepSeek 模型(CC Switch 代理中转)
前端·javascript·人工智能
CoderYanger2 小时前
前端基础——JavaScript(WebAPI)代码案例
java·开发语言·前端·javascript·css·前端框架·html5
恋猫de小郭2 小时前
Shopify 从 React Native 回到 Swift/Kotlin,但是你以为有手就行??
android·前端·ios
BillKu3 小时前
Element Plus 的 el-tab-pane:lazy 的说明
前端·javascript·vue.js
爱勇宝3 小时前
《道德经》第 11 章:真正有用的,常常是你没写出来的那部分
前端·后端·产品