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 包 自上一 ...
随机推荐
- Mysql资料 存储索引
- Linux 编译安装、压缩打包、定时任务
目录 Linux 编译安装 知识储备: wget命令 编译安装 Linux 压缩打包 gzip压缩 bzip2压缩 tar打包 Linux 定时任务 相关文件及操作 Linux 编译安装 编译安装就是 ...
- wustctf2020_number_game
第一次碰到这种类型的题目,特地来记录一下 例行检查就不放了 int的取值范围[-2147482648,2147483647] 网上的解释: 绕过第9行的if即可获取shell,v1是无符号整型,我们输 ...
- 项目的基本概念(Project)
<Project2016 企业项目管理实践>张会斌 董方好 编著 我一看到这个标题就头疼,好吧,又是概念,好在我不要参加相关的考试,否则文字连同标点符号都得背%¥#%#~ 张同学说,项目& ...
- C#面对抽象编程第一讲
闲话不多说,面向对象编程是高级语言的一个特点,但是把它概括成面向抽象更容易直击灵魂,经过了菜鸟大家都要面对的是不要写这么菜的代码了. 上例子,这应该是大家都很熟悉耳熟能详的代码, so easy. 1 ...
- Hexo结合Github搭建个人博客
如何搭建 我采用了ICARUS主题,根据以下教程完成了部署 https://www.cnblogs.com/liuxianan/p/build-blog-website-by-hexo-github. ...
- java 图形化小工具Abstract Window Toolit 常用组件
基本组件 Button: 按钮,可接受单击操作 Canvas: 用于绘图的画布 Checkbox: 复选框组(也可变成单选框组件) CheckboxGroup: 用于将多个checkbox组件组合成一 ...
- SpringBoot使用Aspect切面拦截打印请求参数
引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>sp ...
- 【LeetCode】645. Set Mismatch 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 Hash方法 直接计算 日期 题目地址: https ...
- hdu -4325-Flowers(离散化 线段树)
http://acm.hdu.edu.cn/showproblem.php?pid=4325: 题目意思: 给你N个花开的时间段,然后在有M个时间点,问你在这个时间点有多少花开着. 昨天刚做的一个类似 ...