asp.net core 中优雅的进行响应包装
目录
- 摘要
- 正常响应/模型验证错误包装
- 实现按需禁用包装
- 如何让 Swagger 识别正确的响应包装
- 禁用默认的模型验证错误包装
- 使用方法以及自定义返回结构体
- SourceCode && Nuget package
- 总结
摘要
在 asp.net core 中提供了 Filter 机制,可以在 Action 执行前后进行一些特定的处理,例如模型验证,响应包装等功能就可以在此基础上实现,同时也提供了 ApplicationModel API, 我们可以在此基础上实现选择性的添加 Filter,满足部分接口需要响应特定的结构, 我们常见的 [AllowAnonymous] 正是基于这种机制。同时也将介绍如何让 Swagger 展示正确的包装响应体,以满足第三方对接或前端的代码生成
效果图


正常响应包装
首先我们定义包装体的接口, 这里主要分为正常响应和模型验证失败的响应,其中正常响应分为有数据返回和没有数据返回两种情况,使用接口的目的是为了方便自定义包装体。
public interface IResponseWrapper
{
IResponseWrapper Ok();
IResponseWrapper ClientError(string message);
}
public interface IResponseWrapper<in TResponse> : IResponseWrapper
{
IResponseWrapper<TResponse> Ok(TResponse response);
}
然后根据接口实现我们具体的包装类
没有数据返回的包装体:
/// <summary>
/// Default wrapper for <see cref="EmptyResult"/> or error occured
/// </summary>
public class ResponseWrapper : IResponseWrapper
{
public int Code { get; }
public string? Message { get; }
...
public IResponseWrapper Ok()
{
return new ResponseWrapper(ResponseWrapperDefaults.OkCode, null);
}
public IResponseWrapper BusinessError(string message)
{
return new ResponseWrapper(ResponseWrapperDefaults.BusinessErrorCode, message);
}
public IResponseWrapper ClientError(string message)
{
return new ResponseWrapper(ResponseWrapperDefaults.ClientErrorCode, message);
}
}
有数据返回的包装体:
/// <summary>
/// Default wrapper for <see cref="ObjectResult"/>
/// </summary>
/// <typeparam name="TResponse"></typeparam>
public class ResponseWrapper<TResponse> : ResponseWrapper, IResponseWrapper<TResponse>
{
public TResponse? Data { get; }
public ResponseWrapper()
{
}
private ResponseWrapper(int code, string? message, TResponse? data) : base(code, message)
{
Data = data;
}
public IResponseWrapper<TResponse> Ok(TResponse response)
{
return new ResponseWrapper<TResponse>(ResponseWrapperDefaults.OkCode, null, response);
}
}
然后实现我们的响应包装 Filter,这里分为正常响应包装,和模型验证错误包装两类 Filter,在原本的响应结果 context.Result 的基础上加上我们的包装体
正常响应包装 Filter, 注意处理一下 EmptyResult 的情况,就是常见的返回 Void 或 Task 的场景:
public class ResultWrapperFilter : IResultWrapperFilter
{
private readonly IResponseWrapper _responseWrapper;
private readonly IResponseWrapper<object?> _responseWithDataWrapper;
...
public void OnActionExecuted(ActionExecutedContext context)
{
switch (context.Result)
{
case EmptyResult:
context.Result = new OkObjectResult(_responseWrapper.Ok());
return;
case ObjectResult objectResult:
context.Result = new OkObjectResult(_responseWithDataWrapper.Ok(objectResult.Value));
return;
}
}
}
模型验证错误的 Filter,这里我们将 ErrorMessage 提取出来放在包装体中, 并返回 400 客户端错误的状态码
public class ModelInvalidWrapperFilter : IActionFilter
{
private readonly IResponseWrapper _responseWrapper;
private readonly ILogger<ModelInvalidWrapperFilter> _logger;
...
public void OnActionExecuting(ActionExecutingContext context)
{
if (context.Result == null && !context.ModelState.IsValid)
{
ModelStateInvalidFilterExecuting(_logger, null);
context.Result = new ObjectResult(_responseWrapper.ClientError(string.Join(",",
context.ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage))))
{
StatusCode = StatusCodes.Status400BadRequest
};
}
}
...
}
这里基本的包装结构和 Filter 已经定义完成,但如何实现按需添加 Filter,以满足特定情况下需要返回特定的结构呢?
实现按需禁用包装
回想 asp.net core 中的 权限验证,只有添加了 [AllowAnonymous] 的 Controller/Action 才允许匿名访问,其它接口即使不添加 [Authorize] 同样也会有基础的登录验证,我们这里同样可以使用这种方法实现,那么这一功能是如何实现的呢?
Asp.net core 提供了 ApplicationModel 的 API,会在程序启动时扫描所有的 Controller 类,添加到了 ApplicationModelProviderContext 中,并公开了 IApplicationModelProvider 接口,可以选择性的在 Controller/Action 上添加 Filter,上述功能正是基于该接口实现的,详细代码见 AuthorizationApplicationModelProvider 类,我们可以参照实现自定义的响应包装 Provider 实现在特定的 Controller/Action 禁用包装,并默认给其它接口加上包装 Filter 的功能。
定义禁止包装的接口及 Attribute:
public interface IDisableWrapperMetadata
{
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class DisableWrapperAttribute : Attribute, IDisableWrapperMetadata
{
}
自定义 Provider 实现,这里实现了选择性的添加 Filter,以及后文提到的如何让 Swagger 正确的识别响应包装(详细代码见 Github)
public class ResponseWrapperApplicationModelProvider : IApplicationModelProvider
{
...
public void OnProvidersExecuting(ApplicationModelProviderContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
foreach (var controllerModel in context.Result.Controllers)
{
if (_onlyAvailableInApiController && IsApiController(controllerModel))
{
continue;
}
if (controllerModel.Attributes.OfType<IDisableWrapperMetadata>().Any())
{
if (!_suppressModelInvalidWrapper)
{
foreach (var actionModel in controllerModel.Actions)
{
actionModel.Filters.Add(new ModelInvalidWrapperFilter(_responseWrapper, _loggerFactory));
}
}
continue;
}
foreach (var actionModel in controllerModel.Actions)
{
if (!_suppressModelInvalidWrapper)
{
actionModel.Filters.Add(new ModelInvalidWrapperFilter(_responseWrapper, _loggerFactory));
}
if (actionModel.Attributes.OfType<IDisableWrapperMetadata>().Any()) continue;
actionModel.Filters.Add(new ResultWrapperFilter(_responseWrapper, _genericResponseWrapper));
// support swagger
AddResponseWrapperFilter(actionModel);
}
}
}
...
}
如何让 Swagger 识别正确的响应包装
通过查阅文档可以发现,Swagger 支持在 Action 上添加 [ProducesResponseType] Filter 来显示地指定响应体类型。 我们可以通过上边的自定义 Provider 动态的添加该 Filter 来实现 Swagger 响应包装的识别。
需要注意这里我们通过 ActionModel 的 ReturnType 来取得原响应类型,并在此基础上添加到我们的包装体泛型中,因此我们需要关于 ReturnType 足够多的元数据 (metadata),因此这里推荐返回具体的结构,而不是 IActionResult,当然 Task 这种在这里是支持的。
关键代码如下:
actionModel.Filters.Add(new ProducesResponseTypeAttribute(_genericWrapperType.MakeGenericType(type), statusCode));
禁用默认的模型验证错误包装
默认的模型验证错误是如何添加的呢,答案和 [AllowAnonymous] 类似,都是通过 ApplicationModelProvider 添加上去的,详细代码可以查看 ApiBehaviorApplicationModelProvider 类,关键代码如下:
if (!options.SuppressModelStateInvalidFilter)
{
ActionModelConventions.Add(new InvalidModelStateFilterConvention());
}
可以看见提供了选项可以阻止默认的模型验证错误惯例,关闭后我们自定义的模型验证错误 Filter 就能生效
public static IMvcBuilder AddResponseWrapper(this IMvcBuilder mvcBuilder, Action<ResponseWrapperOptions> action)
{
mvcBuilder.Services.Configure(action);
mvcBuilder.ConfigureApiBehaviorOptions(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
mvcBuilder.Services.TryAddEnumerable(ServiceDescriptor.Transient<IApplicationModelProvider, ResponseWrapperApplicationModelProvider>());
return mvcBuilder;
}
使用方法以及自定义返回结构体
安装 Nuget 包
dotnet add package AspNetCore.ResponseWrapper --version 1.0.1
使用方法:
// .Net5
services.AddApiControllers().AddResponseWrapper();
// .Net6
builder.Services.AddControllers().AddResponseWrapper();
如何实现自定义响应体呢,首先自定义响应包装类,并实现上面提到的响应包装接口,并且需要提供无参的构造函数
自定义响应体:
public class CustomResponseWrapper : IResponseWrapper
{
public bool Success => Code == 0;
public int Code { get; set; }
public string? Message { get; set; }
public CustomResponseWrapper()
{
}
public CustomResponseWrapper(int code, string? message)
{
Code = code;
Message = message;
}
public IResponseWrapper Ok()
{
return new CustomResponseWrapper(0, null);
}
public IResponseWrapper BusinessError(string message)
{
return new CustomResponseWrapper(1, message);
}
public IResponseWrapper ClientError(string message)
{
return new CustomResponseWrapper(400, message);
}
}
public class CustomResponseWrapper<TResponse> : CustomResponseWrapper, IResponseWrapper<TResponse>
{
public TResponse? Result { get; set; }
public CustomResponseWrapper()
{
}
public CustomResponseWrapper(int code, string? message, TResponse? result) : base(code, message)
{
Result = result;
}
public IResponseWrapper<TResponse> Ok(TResponse response)
{
return new CustomResponseWrapper<TResponse>(0, null, response);
}
}
使用方法, 这里以 .Net 6 为例, .Net5 也是类似的
// .Net6
builder.Services.AddControllers().AddResponseWrapper(options =>
{
options.ResponseWrapper = new CustomResponseWrapper.ResponseWrapper.CustomResponseWrapper();
options.GenericResponseWrapper = new CustomResponseWrapper<object?>();
});
SourceCode && Nuget package
SourceCode: https://github.com/huiyuanai709/AspNetCore.ResponseWrapper
Nuget Package: https://www.nuget.org/packages/AspNetCore.ResponseWrapper
总结
本文介绍了 Asp.Net Core 中的通用响应包装的实现,以及如何让 Swagger 识别响应包装,由于异常处理难以做到通用和一致,本文不处理异常情况下的响应包装,读者可以自定义实现 ExceptionFilter。
文章源自公众号:灰原同学的笔记,转载请联系授权
asp.net core 中优雅的进行响应包装的更多相关文章
- 在Asp.NET Core中如何优雅的管理用户机密数据
在Asp.NET Core中如何优雅的管理用户机密数据 背景 回顾 在软件开发过程中,使用配置文件来管理某些对应用程序运行中需要使用的参数是常见的作法.在早期VB/VB.NET时代,经常使用.ini文 ...
- ASP.NET Core 中文文档 第三章 原理(1)应用程序启动
原文:Application Startup 作者:Steve Smith 翻译:刘怡(AlexLEWIS) 校对:谢炀(kiler398).许登洋(Seay) ASP.NET Core 为你的应用程 ...
- ASP.NET Core 中文文档 第三章 原理(6)全球化与本地化
原文:Globalization and localization 作者:Rick Anderson.Damien Bowden.Bart Calixto.Nadeem Afana 翻译:谢炀(Kil ...
- ASP.NET Core中显示自定义错误页面
在 ASP.NET Core 中,默认情况下当发生500或404错误时,只返回http状态码,不返回任何内容,页面一片空白. 如果在 Startup.cs 的 Configure() 中加上 app. ...
- 如何在 ASP.NET Core 中发送邮件
前言 我们知道目前 .NET Core 还不支持 SMTP 协议,当我么在使用到发送邮件功能的时候,需要借助于一些第三方组件来达到目的,今天给大家介绍两款开源的邮件发送组件,它们分别是 MailKit ...
- 在 ASP.NET Core 中执行租户服务
在 ASP.NET Core 中执行租户服务 不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻喷,如觉得我翻译有问题请挪步原博客地址 本博文翻译自: http://gunna ...
- 谈谈ASP.NET Core中的ResponseCaching
前言 前面的博客谈的大多数都是针对数据的缓存,今天我们来换换口味.来谈谈在ASP.NET Core中的ResponseCaching,与ResponseCaching关联密切的也就是常说的HTTP缓存 ...
- ASP.NET Core中使用GraphQL - 第四章 GraphiQL
ASP.NET Core中使用GraphQL ASP.NET Core中使用GraphQL - 第一章 Hello World ASP.NET Core中使用GraphQL - 第二章 中间件 ASP ...
- 如何简单的在 ASP.NET Core 中集成 JWT 认证?
前情提要:ASP.NET Core 使用 JWT 搭建分布式无状态身份验证系统 文章超长预警(1万字以上),不想看全部实现过程的同学可以直接跳转到末尾查看成果或者一键安装相关的 nuget 包 自上一 ...
随机推荐
- 什么是API?
一.简介 API(Application Programming Interface,应用程序编程接口)是一些预先定义的函数,目的是提供应用程序,与开发人员基于某软件或硬件得以访问一组例程的能力,而又 ...
- 追踪工具strace
目录 一.简介 二.例子 找出程序读取的文件 查看现在程序在做什么 查看程序中哪个部分消耗大量cpu 无法连接服务器查看信息 一.简介 Linux 操作系统有很多用来跟踪程序行为的工具,内核态的函数调 ...
- View的简单说明
一)三个结构体:CGPoint.CGSize.CGRect 1. CGPoint struct CGPoint { CGFloat x; CGFloat y; }; typedef struct CG ...
- JDK ThreadPoolExecutor核心原理与实践
一.内容概括 本文内容主要围绕JDK中的ThreadPoolExecutor展开,首先描述了ThreadPoolExecutor的构造流程以及内部状态管理的机理,随后用大量篇幅深入源码探究了Threa ...
- 『学了就忘』Linux系统定时任务 — 87、只执行一次的定时任务
目录 1.at服务管理 2.at命令的访问控制 3.at命令 4.其他at管理命令 5.总结 定时任务是在服务器上常用到的一个工作. 在你指定的时间,系统会自动执行你指定的程序(脚本或者命令). Li ...
- java 8 启动脚本优化 2
#!/bin/bash #链接文件 source /etc/profile #java虚拟机启动参数 #通过http://xxfox.perfma.com/jvm/check来检查参数的合理性 JAV ...
- ORM-数据库命令操作包装实例对象学习
http://www.cnblogs.com/alex3714/articles/5978329.html python 之路,Day11 - sqlalchemy ORM 本节内容 ORM介绍 ...
- Linux使用tar解压的时候去掉父级目录
去除解压目录结构使用 --strip-components N 如: 压缩文件text.tar 中文件信息为 src/src1/src2/text.txt 运行 tar -zxvf text.tar ...
- 使用docker logs -f 打印日志中文无法正常显示
打印docker日志的时候 中文无法显示 显示了问号 在Dockerfile加入 ENV LANG en_US.UTF-8 ENV LANGUAGE en_US:en ENV LC_ALL en_US ...
- Android NDK开发篇:Java与原生代码通信(数据操作)
虽然说使用NDK可以提高Android程序的执行效率,但是调用起来还是稍微有点麻烦.NDK可以直接使用Java的原生数据类型,而引用类型,因为Java的引用类型的实现在NDK被屏蔽了,所以在NDK使用 ...