Asp.net Core 异常日志与API返回值处理
需求:
1、对异常进行捕获记录日志 并且修改返回值给前端
解释:
ILogger4是自定义的一个日志,更改它就好
解决方案1:
使用中间件进行异常捕获并且修改其返回值
public class ErrorMiddleware
{
private readonly RequestDelegate _next;
ILogger4<ErrorMiddleware> logger4;
public ErrorMiddleware(RequestDelegate next,ILogger4<ErrorMiddleware> logger4)
{
_next = next;
this.logger4 = logger4;
} public async Task Invoke(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception e)
{
logger4.LogError(e,e.Message+"\r\n"+e.StackTrace);
throw e;
} }
}
这一步简单,从源码里 ExceptionHandlerMiddleware.cs类里 Copy的代码
使用中间件进行修改返回值
public class ResultMiddleware
{
private readonly RequestDelegate _next; public ResultMiddleware(RequestDelegate next)
{
_next = next;
} public async Task Invoke(HttpContext httpContext)
{ await _next(httpContext);
string bodyString = "<p>不好意思 系统正在升级维护 请稍后再试</p>";
var by = Encoding.UTF8.GetBytes(bodyString);
var heard =(Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpResponseHeaders)httpContext.Response.Headers;
heard.HeaderContentLength = by.Length.ToString();
//必须要手动设置请求头的ContentLength大小 才能修改返回值的数据
await httpContext.Response.Body.WriteAsync(by);
}
}
这是从网上copy 修改的代码,不推荐使用 开销太大 转为过滤器
解决方案2:
使用中间件进行异常捕获并且修改其返回值
异常过滤器
/// <summary>
/// 异常过滤器
/// </summary>
public class ErrorFilter :Attribute,IExceptionFilter
{ ILogger4<ErrorFilter> logger4;
/// <summary>
/// 标签
/// </summary>
public ErrorFilter() {
} /// <summary>
/// 全局配置
/// </summary>
/// <param name="logger4"></param>
public ErrorFilter(ILogger4<ErrorFilter> logger4) {
this.logger4 = logger4;
} public void OnException(ExceptionContext context)
{
var e = context.Exception;
logger4.LogError(e, e.Message + "\r\n" + e.StackTrace);
context.Result = new JsonResult(new BaseResult(e.Message));
}
}
方法过滤器
/// <summary>
/// 对打上该标记的 返回结果为JsonResult的请求进行Result包装
/// </summary>
public class ApiResultFilter : Attribute, IActionFilter
{
/// <summary>
/// 执行方法体之后
/// </summary>
/// <param name="context"></param>
public void OnActionExecuted(ActionExecutedContext context)
{ var result = context.Result;
if (result!=null &&result is JsonResult resulta)
{
context.Result = new JsonResult(new BaseResult(resulta.Value));
} } /// <summary>
/// 执行方法体之前
/// </summary>
/// <param name="context"></param>
public void OnActionExecuting(ActionExecutingContext context)
{
//不做修改
}
}
可以使用标签的方法
/// <summary>
/// 测试 返回过滤器
/// </summary>
/// <returns></returns>
[ErrorFilter]
[ApiResultFilter]
[HttpGet]
public IActionResult TestReuslt()
{
throw new Exception("AA");
var obj = new
{
A = ""
};
return Json(obj);
}
也可以使用全局配置的方法
//注册过滤器
services.AddSingleton<ApiResultFilter>();
services.AddSingleton<ErrorFilter>(); services.AddMvc(
config => {
config.Filters.AddService(typeof(ApiResultFilter));
config.Filters.AddService(typeof(ErrorFilter));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
注意:
打上的标签无法获取IOC容器
不要使用全局配置与标签一起使用 会造成多次调用
在这里推荐使用过滤器而不是中间件,
贴上一张大佬的过滤器调用图
结果:
Asp.net Core 异常日志与API返回值处理的更多相关文章
- ASP.NET Core中的Action的返回值类型
在Asp.net Core之前所有的Action返回值都是ActionResult,Json(),File()等方法返回的都是ActionResult的子类.并且Core把MVC跟WebApi合并之后 ...
- 从头编写 asp.net core 2.0 web api 基础框架 (3)
第一部分:http://www.cnblogs.com/cgzl/p/7637250.html 第二部分:http://www.cnblogs.com/cgzl/p/7640077.html 之前我介 ...
- 【转载】从头编写 asp.net core 2.0 web api 基础框架 (3)
Github源码地址:https://github.com/solenovex/Building-asp.net-core-2-web-api-starter-template-from-scratc ...
- 从头编写 asp.net core 2.0 web api 基础框架 (1)
工具: 1.Visual Studio 2017 V15.3.5+ 2.Postman (Chrome的App) 3.Chrome (最好是) 关于.net core或者.net core 2.0的相 ...
- 【转载】从头编写 asp.net core 2.0 web api 基础框架 (1)
工具: 1.Visual Studio 2017 V15.3.5+ 2.Postman (Chrome的App) 3.Chrome (最好是) 关于.net core或者.net core 2.0的相 ...
- 使用 ASP.NET Core MVC 创建 Web API(四)
使用 ASP.NET Core MVC 创建 Web API 使用 ASP.NET Core MVC 创建 Web API(一) 使用 ASP.NET Core MVC 创建 Web API(二) 使 ...
- 从零开始学习 asp.net core 2.1 web api 后端api基础框架(二)-创建项目
原文:从零开始学习 asp.net core 2.1 web api 后端api基础框架(二)-创建项目 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.ne ...
- 【ASP.NET Core学习】Web API
这里介绍在ASP.NET Core中使用Web API创建 RESTful 服务,本文使用VSCode + NET Core3.0 创建简单Rest API 格式化输出 JSON Patch请求 Op ...
- 如何利用Serilog的RequestLogging来精简ASP.NET Core的日志输出
这是该系列的第一篇文章:在ASP.NET Core 3.0中使用Serilog.AspNetCore. 第1部分-使用Serilog RequestLogging来简化ASP.NET Core的日志输 ...
随机推荐
- 力扣(LeetCode)从不订购的客户-数据库题 个人题解
SQL架构 某网站包含两个表,Customers 表和 Orders 表.编写一个 SQL 查询,找出所有从不订购任何东西的客户. Customers 表: +----+-------+ | Id | ...
- Easy 2048 Again(状压dp)
题目链接: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3802 题意: 从数列A中, 删除若干个数(可以0个), 是删除 ...
- requirements.txt的创建及使用
python的包管理 pip方式: 创建 (venv) $ pip freeze >requirements.txt 执行 (venv) $ pip install -r requirement ...
- IntelliJ IDEA使用报错
GZIPResponseStream不是抽象的, 并且未覆盖javax.servlet.ServletOutputStream中 继承了某个抽象类, 或者 实现某个接口这时候你必须 把基类或接口中的所 ...
- Openlayers Projection导致经纬度颠倒问题
问题: openlayers3调用TileWMS接口,实现Openlayers加载Geoserver转发的ArcGIS切片时,web墨卡托(wkid3857)没有问题,但是WGS84(wkid4326 ...
- Python 并发总结,多线程,多进程,异步IO
1 测量函数运行时间 import time def profile(func): def wrapper(*args, **kwargs): import time start = time.tim ...
- springboot+swagger接口文档企业实践(下)
目录 1.引言 2. swagger接口过滤 2.1 按包过滤(package) 2.2 按类注解过滤 2.3 按方法注解过滤 2.4 按分组过滤 2.4.1 定义注解ApiVersion 2.4.2 ...
- JavaScript笔记十
1.正则表达式 - 语法: - 量词 {n} 正好n次 {m,n} m-n次 {m,} 至少m次 + 至少1次 {1,} ? 0次或1次 {0,1} * 0次或多次 {0,} - 转义字符 \ 在正则 ...
- 向mysql数据表中插入数据失败的原因
1.案例代码: $sql1="insert into content(category,subject,content,username,release_date) values('{$ca ...
- ios中数据存储方式
以上三种不能存储大批量数据 plist只能先取出来 里面的数据 覆盖存储 SQLLite3 数据库 纯C语言 轻量级 CoreData 基于SQLLite3 OC版本 重量级 大批量数据缓存 SQL ...