ASP.NET Core WebApi 返回统一格式参数
2023-02-18 15:32:19 时间
业务场景:
业务需求要求,需要对 WebApi 接口服务统一返回参数,也就是把实际的结果用一定的格式包裹起来,比如下面格式:
{
"response":{
"code":200,
"msg":"Remote service error",
"result":""
}
}
具体实现:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
public class WebApiResultMiddleware : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext context)
{
//根据实际需求进行具体实现
if (context.Result is ObjectResult)
{
var objectResult = context.Result as ObjectResult;
if (objectResult.Value == null)
{
context.Result = new ObjectResult(new { code = 404, sub_msg = "未找到资源", msg = "" });
}
else
{
context.Result = new ObjectResult(new { code = 200, msg = "", result = objectResult.Value });
}
}
else if (context.Result is EmptyResult)
{
context.Result = new ObjectResult(new { code = 404, sub_msg = "未找到资源", msg = "" });
}
else if (context.Result is ContentResult)
{
context.Result = new ObjectResult(new { code = 200, msg = "", result= (context.Result as ContentResult).Content });
}
else if (context.Result is StatusCodeResult)
{
context.Result = new ObjectResult(new { code = (context.Result as StatusCodeResult).StatusCode, sub_msg = "", msg = "" });
}
}
}
Startup
添加对应配置:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(typeof(WebApiResultMiddleware));
options.RespectBrowserAcceptHeader = true;
});
}
相关文章
- Redis事件循环
- Grafana 系列文章(一):基于 Grafana 的全栈可观察性 Demo
- Docker 基础 - 3
- Docker 基础 - 2
- Docker 基础 - 1
- Crossplane - 比 Terraform 更先进的云基础架构管理平台?
- Cert Manager 申请SSL证书流程及相关概念-三
- Cert Manager 申请SSL证书流程及相关概念-二
- Cert Manager 申请 SSL 证书流程及相关概念 - 一
- APM vs NPM
- API 网关的功能用途及实现方式
- Ansible 学习笔记 - 批量巡检站点 URL 状态
- Ansible 学习笔记 - 定位主机和组的模式
- 制作容器镜像的最佳实践
- 在 NGINX 中根据用户真实 IP 进行限制
- 在 K8S Volume 中使用 subPath
- 我的基于 JamStack 的新博客
- 使用Prometheus监控docker compose方式部署的ES
- 使用 K8S 部署 RSS 全套自托管解决方案- RssHub + Tiny Tiny Rss
- 使用Jiralert实现AlertManager告警对接Jira