.NET 中如何实现 Web API 标准化响应模型
|
admin
2024年11月22日 14:32
本文热度 2332
|
前言
随着微服务的不断发展,开发 Web API 并提供一致且清晰的响应模型对开发人员和用户都至关重要。标准化的响应不仅使可以使用 API 更易于使用,而且还能提高其可维护性。本文将探讨在 .NET Core Web API 创建标准化响应的过程,实现管理 API 响应和处理错误的实例。
标准响应模型
一致性的 API 响应对于 Web APP 很关键。引入标准化响应模型可确保请求端以预测的格式接收响应,无论请求是否成功。现在从定义一个标准模型(ResponseModel<T>)开始,该模型封装了成功和错误场景。
标准响应模型通常包括以下内容:
定义标准化响应模型的简单示例:
public class ResponseModel<T>{ /// <summary> /// 状态 /// </summary> public bool Status { get; set; } /// <summary> /// 消息 /// </summary> public string Message { get; set; } /// <summary> /// 保存响应数据 /// </summary> public T Data { get; set; } /// <summary> /// 异常 /// </summary> public List<string> Errors { get; set; } /// <summary> /// /// </summary> public ResponseModel() { Status = true; }}
模型实现步骤
1、创建响应标准模型类
定义一个可以处理不同类型数据的泛型类ResponseModel<T>,其包括 Status、Message、Data、Errors 等属性。可参考上面的示例。
2、在 Controller 服务中实现响应模型
定义Customer服务的Controller类,方法分别是GetCustomerById 和 CreateCustomer。这二个方法分别为 GET API 的方法与POST API 的方法。
public class CustomerModel{ /// <summary> /// ID /// </summary> public int CustomerId {get; set;} /// <summary> /// 名称 /// </summary> public string CustomerName {get; set;} /// <summary> /// 简称 /// </summary> public string CustomerShort {get; set;} /// <summary> /// 城市 /// </summary> public string City {get; set;} /// <summary> /// 等级 /// </summary> public string Grade {get; set;}}
using Microsoft.AspNetCore.Mvc;
namespace Fountain.WebAPI.JwtTokenDemo.Controllers{ [Route("api/[controller]")] [ApiController] public class CustomerController : ControllerBase { /// <summary> /// /// </summary> [HttpGet("{id}")] public async Task<IActionResult> GetCustomerById(int id) { ResponseModel<CustomerModel> response = new ResponseModel<CustomerModel>();
try { CustomerModel item = await itemService.GetItemByIdAsync(id); if (item == null) { response.Status = false; response.Message = "客户档案不存在"; // 返回响应 return NotFound(response); }
response.Status = true; response.Message = "Success"; response.Data = item; // 返回响应 return Ok(response); } catch (Exception ex) { response.Status = false; response.Message = "Failure"; List<string> error = new List<string>(); error.Add(ex.Message); // 返回响应 response.Errors = error; return StatusCode(500, response); } } }}
using Microsoft.AspNetCore.Mvc;
namespace Fountain.WebAPI.JwtTokenDemo.Controllers{ [Route("api/[controller]")] [ApiController] public class CustomerController : ControllerBase { [HttpPost] public async Task<IActionResult> CreateCustomer(CustomerModel customer) { ResponseModel<string> response = new ResponseModel<string>(); try { itemService.CreateCustomer(customer); response.Data = null; response.Status = true; response.Message = "success"; return Ok(response); } catch (Exception ex) { response.Status = false; response.Message = "Failure"; response.Data = null; List<string> error = new List<string>(); error.Add(ex.Message); // 返回响应 response.Errors = error; return StatusCode(500, response); } } }}
3、简单说明
ResponseModel 使用泛型的设计,允许响应模型处理任何类型的数据,使其具有极强的通用性和可重用性。无论您的 API 需要返回简单字符串、复杂对象还是项目集合,通用数据类型参数 <T> 都可以确保标准响应模型可以无缝地适应它。
小结
以上是 ASP.NET Core Web API ,使用 C# 实现标准响应模型的具体步骤。通过使用标准响应可以增强用户体验、简化调试并确保Web API的可靠性。希望本文对您有所收获,如有不到之处,请多多包涵。
该文章在 2024/11/22 17:03:14 编辑过