目录

  • 摘要
  • 正常响应/模型验证错误包装
  • 实现按需禁用包装
  • 如何让 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();

如何实现自定义响应体呢,首先自定义响应包装类,并实现上面提到的响应包装接口,并且需要提供无参的构造函数

示例代码: https://github.com/huiyuanai709/AspNetCore.ResponseWrapper/tree/main/samples/CustomResponseWrapper/ResponseWrapper

自定义响应体:

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 中优雅的进行响应包装的更多相关文章

  1. 在Asp.NET Core中如何优雅的管理用户机密数据

    在Asp.NET Core中如何优雅的管理用户机密数据 背景 回顾 在软件开发过程中,使用配置文件来管理某些对应用程序运行中需要使用的参数是常见的作法.在早期VB/VB.NET时代,经常使用.ini文 ...

  2. ASP.NET Core 中文文档 第三章 原理(1)应用程序启动

    原文:Application Startup 作者:Steve Smith 翻译:刘怡(AlexLEWIS) 校对:谢炀(kiler398).许登洋(Seay) ASP.NET Core 为你的应用程 ...

  3. ASP.NET Core 中文文档 第三章 原理(6)全球化与本地化

    原文:Globalization and localization 作者:Rick Anderson.Damien Bowden.Bart Calixto.Nadeem Afana 翻译:谢炀(Kil ...

  4. ASP.NET Core中显示自定义错误页面

    在 ASP.NET Core 中,默认情况下当发生500或404错误时,只返回http状态码,不返回任何内容,页面一片空白. 如果在 Startup.cs 的 Configure() 中加上 app. ...

  5. 如何在 ASP.NET Core 中发送邮件

    前言 我们知道目前 .NET Core 还不支持 SMTP 协议,当我么在使用到发送邮件功能的时候,需要借助于一些第三方组件来达到目的,今天给大家介绍两款开源的邮件发送组件,它们分别是 MailKit ...

  6. 在 ASP.NET Core 中执行租户服务

    在 ASP.NET Core 中执行租户服务 不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻喷,如觉得我翻译有问题请挪步原博客地址 本博文翻译自: http://gunna ...

  7. 谈谈ASP.NET Core中的ResponseCaching

    前言 前面的博客谈的大多数都是针对数据的缓存,今天我们来换换口味.来谈谈在ASP.NET Core中的ResponseCaching,与ResponseCaching关联密切的也就是常说的HTTP缓存 ...

  8. ASP.NET Core中使用GraphQL - 第四章 GraphiQL

    ASP.NET Core中使用GraphQL ASP.NET Core中使用GraphQL - 第一章 Hello World ASP.NET Core中使用GraphQL - 第二章 中间件 ASP ...

  9. 如何简单的在 ASP.NET Core 中集成 JWT 认证?

    前情提要:ASP.NET Core 使用 JWT 搭建分布式无状态身份验证系统 文章超长预警(1万字以上),不想看全部实现过程的同学可以直接跳转到末尾查看成果或者一键安装相关的 nuget 包 自上一 ...

随机推荐

  1. 如何用CodeBlocks调试?

    一.简介 这篇文章我主要会介绍CodeBlocks的调试功能,并简单讲述如何使用它. 二.前言 大家好,最近和小伙伴们讨论修改程序的时候,我突然想到,授人以鱼不如授人以渔(指调试),于是这篇文章应运而 ...

  2. <转>Hadoop入门总结

    转自:http://www.cnblogs.com/skyme/archive/2012/06/01/2529855.html 第1章 引言 1.1 编写目的 对关于hadoop的文档及资料进行进一步 ...

  3. Linux编译安装、压缩打包、定时任务管理

    编译安装 压缩打包 定时任务管理 一.编译安装 使用源代码,编译打包软件 1.特点 1.可以定制软件 2.按需构建软件 2.编译安装 1.下载源代码包 wget https://nginx.org/d ...

  4. CF1130A Be Positive 题解

    Content 有一个长度为 \(n\) 的数组 \(a_1,a_2,a_3,...,a_n\),试找出一个数 \(d\),使得数组中的每个数除以 \(d\) 得到的 \(n\) 个结果中至少有 \( ...

  5. UiPath RPA培训2021.4版本解读 (2021年5月)-RPA学习天地

    2021年5月26日Ui Path发布了新产品2021.4版本,我们来看看有什么新功能: 说明一下uipath的版本发布节奏: uipath的版本一般是每年发布2个版本,其中5月份发布的一般是FTS版 ...

  6. 【LeetCode】363. Max Sum of Rectangle No Larger Than K 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/max-sum- ...

  7. Codeforces Round #327 (Div. 1), problem: (A) Median Smoothing

    http://codeforces.com/problemset/problem/590/A: 在CF时没做出来,当时直接模拟,然后就超时喽. 题意是给你一个0 1串然后首位和末位固定不变,从第二项开 ...

  8. LeetCode118. Pascal's Triangle 杨辉三角

    题目 给定行数,生成对应的杨辉三角 思考 同一行是对称的,最大的下标为(行数+1)/2;1,1,2,3,6;下标从0开始,则对应分别为0.0.1.1.2.2 对于第偶数行,个数也是偶数,对于奇数行,个 ...

  9. 1678 lyk与gcd

    1678 lyk与gcd 基准时间限制:2 秒 空间限制:131072 KB 这天,lyk又和gcd杠上了.它拥有一个n个数的数列,它想实现两种操作. 1:将  ai 改为b.2:给定一个数i,求所有 ...

  10. 1083 - Histogram

    1083 - Histogram   PDF (English) Statistics Forum Time Limit: 2 second(s) Memory Limit: 64 MB A hist ...