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 ...
随机推荐
- That's not my Neighbor 之 Chester 问题答案
Q: What is the meaning of life, the universe and everything else? A: 42 参见:生命.宇宙以及任何事情的终极答案 Q: What ...
- (Ljava/lang/String;)Ljava/util/List;
背景:原正常代码,更改类名后,重新运行 报错:(Ljava/lang/String;)Ljava/util/List; 解决:mvn clean 后 compile,再运行,正常
- ECMA Script6 中的 尾调用优化
在读 <深入理解ES6>一书中,看到有关函数的 "尾调用优化" 章节,特此记录一下 尾调用 指的是 函数作为另一个函数的最后一条语句被调用: function foo ...
- Vue3 动态子页面和菜单栏同步
动态子页面 <router-view></router-view>显示子页面的内容 main.vue <template> <a-layout id=&quo ...
- CCIA数安委等组织发布PIA星级标识名单,合合信息再次通过数据安全领域权威评估
CCIA数安委等组织发布PIA星级标识名单,合合信息再次通过数据安全领域权威评估 近期,"中国网络安全产业联盟(CCIA)数据安全工作委员会"."数据安全共同体计划( ...
- Angular 18+ 高级教程 – Angular Compiler (AKA ngc) Quick View
前言 在 Get Started 那一篇,我们提到过 Angular Compilation.这篇稍微给点具体画面,让大家感受一下. 但不会讲细节,对细节感兴趣的可以看这篇 Medium – How ...
- SQL Server Aggregate Functions
SUM 如果 row count = 0 返回的是 NULL 而不是 0 哦, 如果要 0 可以使用 ISNULL 来处理 如果其中一些 row 是 NULL, 那无所谓, 它只会 SUM 数字出来 ...
- manim边学边做--弧形多边形
弧形多边形是一种结合了圆弧和多边形的图形,这类几何图形在设计中应用非常广泛. 比如在家居设计中,看看家里的沙发,餐桌和座椅等,它们的边角,靠背等地方都是弧形的设计,这种设计有效柔化了室内空间,使整体氛 ...
- C#|.net core 基础 - 值传递 vs 引用传递
不知道你在开发过程中有没有遇到过这样的困惑:这个变量怎么值被改?这个值怎么没变? 今天就来和大家分享可能导致这个问题的根本原因值传递 vs 引用传递. 在此之前我们先回顾两组基本概念: 值类型 vs ...
- Tomcat——配置、部署
配置 修改启动端口号:conf/sever.xml HTTP协议默认端口号为80,若将Tomcat端口号改为80,则将来访问Tomcat时,不用输入端口号 端口号改 ...