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 });
}
}