Abp Vnext 中如何统一接口返回值
ABP Vnext Vue 的实现
在使用 abp 的过程中,如果提供给第三方接口要实现返回值统一需要怎么做?
{
// 返回格式类似这种
"success": false,
"message": "请求失败",
"data": null,
"code": 500
}
- 定义返回类型
public class WrapResult<T>
{
private bool Success { get; set; }
private string Message { get; set; }
private T Data { get; set; }
private int Code { get; set; }
public WrapResult()
{
Success = true;
Message = "Success";
Data = default;
Code = 200;
}
public void SetSuccess(T data, string message = "Success", int code = 200)
{
Success = true;
Data = data;
Code = code;
}
public void SetFail(string message = "Fail", int code = 500)
{
Success = false;
Message = message;
Code = code;
}
}
实现思路
- 定义 WrapResultAttribute
public class WrapResultAttribute : Attribute
{
}
- 实现 IAsyncExceptionFilter(拦截异常,抛异常时指定返回格式)
public class ResultExceptionFilter : IFilterMetadata, IAsyncExceptionFilter, ITransientDependency
{
private ILogger<ResultExceptionFilter> Logger { get; set; }
private readonly IExceptionToErrorInfoConverter _errorInfoConverter;
private readonly IHttpExceptionStatusCodeFinder _statusCodeFinder;
private readonly IJsonSerializer _jsonSerializer;
private readonly AbpExceptionHandlingOptions _exceptionHandlingOptions;
public ResultExceptionFilter(
IExceptionToErrorInfoConverter errorInfoConverter,
IHttpExceptionStatusCodeFinder statusCodeFinder,
IJsonSerializer jsonSerializer,
IOptions<AbpExceptionHandlingOptions> exceptionHandlingOptions)
{
_errorInfoConverter = errorInfoConverter;
_statusCodeFinder = statusCodeFinder;
_jsonSerializer = jsonSerializer;
_exceptionHandlingOptions = exceptionHandlingOptions.Value;
Logger = NullLogger<ResultExceptionFilter>.Instance;
}
public async Task OnExceptionAsync(ExceptionContext context)
{
if (!ShouldHandleException(context))
{
return;
}
await HandleAndWrapException(context);
}
protected virtual bool ShouldHandleException(ExceptionContext context)
{
if (context.ActionDescriptor.AsControllerActionDescriptor().ControllerTypeInfo.GetCustomAttributes(typeof(WrapResultAttribute), true).Any())
{
return true;
}
if (context.ActionDescriptor.GetMethodInfo().GetCustomAttributes(typeof(WrapResultAttribute), true).Any())
{
return true;
}
return false;
}
protected virtual async Task HandleAndWrapException(ExceptionContext context)
{
// 处理异常信息
context.HttpContext.Response.Headers.Add(AbpHttpConsts.AbpErrorFormat, "true");
var statusCode = (int)_statusCodeFinder.GetStatusCode(context.HttpContext, context.Exception);
context.HttpContext.Response.StatusCode = 200;
var remoteServiceErrorInfo = _errorInfoConverter.Convert(context.Exception, _exceptionHandlingOptions.SendExceptionsDetailsToClients);
remoteServiceErrorInfo.Code = context.HttpContext.TraceIdentifier;
remoteServiceErrorInfo.Message = SimplifyMessage(context.Exception);
// 返回格式统一
var result = new WrapResult<object>();
result.SetFail(remoteServiceErrorInfo.Message);
// HttpResponse
context.Result = new ObjectResult(result);
// 写日志
var logLevel = context.Exception.GetLogLevel();
var remoteServiceErrorInfoBuilder = new StringBuilder();
remoteServiceErrorInfoBuilder.AppendLine($"---------- {nameof(RemoteServiceErrorInfo)} ----------");
remoteServiceErrorInfoBuilder.AppendLine(_jsonSerializer.Serialize(remoteServiceErrorInfo, indented: true));
Logger.LogWithLevel(logLevel, remoteServiceErrorInfoBuilder.ToString());
Logger.LogException(context.Exception, logLevel);
await context.HttpContext
.RequestServices
.GetRequiredService<IExceptionNotifier>()
.NotifyAsync(
new ExceptionNotificationContext(context.Exception)
);
context.Exception = null; //Handled!
}
private string SimplifyMessage(Exception error)
{
string message = string.Empty;
switch (error)
{
case AbpAuthorizationException e:
return message = "Authenticate failure!";
case AbpValidationException e:
return message = "Request param validate failure!";
case EntityNotFoundException e:
return message = "not found the entity!";
case BusinessException e:
return message = $"{e.Message}";
case NotImplementedException e:
return message = "not implement!";
default:
return message = "server internal error!";
}
}
}
注册 Filter
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddMvc(options =>
{
options.Filters.Add(typeof(ResultExceptionFilter));
});
}
使用
- 在 Controller 上或者 Action 上打上 WrapResultAttribute 特性
- 例如
[Route("Permissions")]
[WrapResult]
public class PermissionController : AbpProController,IRolePermissionAppService
{
private readonly IRolePermissionAppService _rolePermissionAppService;
public PermissionController(IRolePermissionAppService rolePermissionAppService)
{
_rolePermissionAppService = rolePermissionAppService;
}
[HttpPost("tree")]
[SwaggerOperation(summary: "获取角色权限", Tags = new[] { "Permissions" })]
[WrapResult] //控制器上打了 action上就不需要
public Task<PermissionOutput> GetPermissionAsync(GetPermissionInput input)
{
return _rolePermissionAppService.GetPermissionAsync(input);
}
}
Abp Vnext 中如何统一接口返回值的更多相关文章
- .NetCore Web Api 利用ActionFilterAttribute统一接口返回值格式
.Net Core 同 Asp.Net MVC一样有几种过滤器,这里不再赘述每个过滤器的执行顺序与作用. 在实际项目开发过程中,统一API返回值格式对前端或第三方调用将是非常必要的,在.NetCore ...
- 为什么阿里巴巴Java开发手册中强制要求接口返回值不允许使用枚举?
在阅读<阿里巴巴Java开发手册>时,发现有一条关于二方库依赖中接口返回值不允许使用枚举类型的规约,具体内容如下: 在谈论为什么之前先来科普下什么是二方库,二方库也称作二方包,一般指公司内 ...
- nginx访问日志中添加接口返回值
因为nginx作为web服务器时,会代理后端的一些接口,这时访问日志中只能记录访问接口的status码,也就是说,只能获得200.404 这些的值 那么如何获得接口返回的response值呢? 下面开 ...
- C#进阶系列——WebApi 接口返回值不困惑:返回值类型详解
前言:已经有一个月没写点什么了,感觉心里空落落的.今天再来篇干货,想要学习Webapi的园友们速速动起来,跟着博主一起来学习吧.之前分享过一篇 C#进阶系列——WebApi接口传参不再困惑:传参详解 ...
- WebApi 接口返回值类型详解 ( 转 )
使用过Webapi的园友应该都知道,Webapi的接口返回值主要有四种类型 void无返回值 IHttpActionResult HttpResponseMessage 自定义类型 此篇就围绕这四块分 ...
- WebApi接口返回值不困惑:返回值类型详解
前言:已经有一个月没写点什么了,感觉心里空落落的.今天再来篇干货,想要学习Webapi的园友们速速动起来,跟着博主一起来学习吧.作为程序猿,我们都知道参数和返回值是编程领域不可分割的两大块,此前分享了 ...
- Asp.Net WebApi接口返回值IHttpActionResult
WebApi是微软在VS2012 MVC4版本中绑定发行的,webapi2.0同mvc5发行的 webapi一共有以下接口返回值 1.void无返回值2.IHttpActionResult Json( ...
- WebApi 接口返回值不困惑:返回值类型详解。IHttpActionResult、void、HttpResponseMessage、自定义类型
首先声明,我还没有这么强大的功底,只是感觉博主写的很好,就做了一个复制,请别因为这个鄙视我,博主网址:http://www.cnblogs.com/landeanfen/p/5501487.html ...
- (转)C# WebApi 接口返回值不困惑:返回值类型详解
原文地址:http://www.cnblogs.com/landeanfen/p/5501487.html 正文 前言:已经有一个月没写点什么了,感觉心里空落落的.今天再来篇干货,想要学习Webapi ...
- [转]C#进阶系列——WebApi 接口返回值不困惑:返回值类型详解
本文转自:http://www.cnblogs.com/landeanfen/p/5501487.html 阅读目录 一.void无返回值 二.IHttpActionResult 1.Json(T c ...
随机推荐
- 2024-08-28:用go语言,给定一个从1开始、长度为n的整数数组nums,定义一个函数greaterCount(arr, val)可以返回数组arr中大于val的元素数量。 按照以下规则进行n次
2024-08-28:用go语言,给定一个从1开始.长度为n的整数数组nums,定义一个函数greaterCount(arr, val)可以返回数组arr中大于val的元素数量. 按照以下规则进行n次 ...
- 远距离跨网络实现windows远程桌面连接
1.保证已经打开被连接电脑---远程访问---权限. 我的电脑--右键--属性--远程设置 2.选择允许连接 (选择用户和高级没有特殊设置可以不动,被连接电脑当前登陆的账号就可以满足权限) 3.打开- ...
- 今日算法随笔:填充每个节点的下一个右侧节点指针 II
题目链接:117. 填充每个节点的下一个右侧节点指针 II 题目描述 给定一个二叉树,填充它的每个 next 指针,让这个指针指向其下一个右侧节点.如果找不到下一个右侧节点,则将 next 指针设置为 ...
- RS485与ModbusRTU
前言 大家好!我是付工. 每次听到别人说RS485通信协议,就很想去纠正他. 今天跟大家聊聊关于RS485的那些事. 接口标准 首先明确一点,RS485不是通信协议,而是一种接口标准,它还有2个兄弟: ...
- 解密Prompt系列38.多Agent路由策略
常见的多智能体框架有几类,有智能体相互沟通配合一起完成任务的例如ChatDev,CAMEL等协作模式, 还有就是一个智能体负责一类任务,通过选择最合适的智能体来完成任务的路由模式,当然还有一些多智能体 ...
- SpringMVC —— SpringMVC简介
SpringMVC SpringMVC技术 与 Servlet技术功能等同,均属于web层开发技术 是一种基于java实现MVC模型的轻量级Web框架 SpringMVC 入门案例 ...
- LeetCode 1349. 参加考试的最大学生数 (状压DP 或 二分图最大独立子集)
给你一个 m * n 的矩阵 seats 表示教室中的座位分布.如果座位是坏的(不可用),就用 '#' 表示:否则,用 '.' 表示. 学生可以看到左侧.右侧.左上.右上这四个方向上紧邻他的学生的答卷 ...
- mmap映射类型
文件映射和匿名映射都是操作系统中对于内存映射的两种类型,主要应用于进程间的通信或者大量数据的处理. 文件映射,也就是内存映射文件,是把一个文件或者文件的一部分映射到进程的地址空间,它允许对文件进行随机 ...
- NET Core 基础 - 删除字符串最后一个字符的七大类N种实现方式
今天想通过和大家分享如何删除字符串最后一个字符的N种实现方法,来回顾一些基础知识点. 01.第一类.字符串方式 这类方法是通过string类型自身方法直接实现. 1.Substring方法 相信大多数 ...
- 2023年8月中国数据库排行榜:TiDB 重夺榜眼,PolarDB 再进一位
斗力频催鼓.争都更少筹. 2023年8月的 墨天轮中国数据库流行度排行 在炎炎夏日中火热出炉,本月共有286个数据库参与排名.本月排行榜前十中,头部变动加剧.TiDB 发奋图强重夺榜眼,阿里云Pola ...