需求:

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返回值处理的更多相关文章

  1. ASP.NET Core中的Action的返回值类型

    在Asp.net Core之前所有的Action返回值都是ActionResult,Json(),File()等方法返回的都是ActionResult的子类.并且Core把MVC跟WebApi合并之后 ...

  2. 从头编写 asp.net core 2.0 web api 基础框架 (3)

    第一部分:http://www.cnblogs.com/cgzl/p/7637250.html 第二部分:http://www.cnblogs.com/cgzl/p/7640077.html 之前我介 ...

  3. 【转载】从头编写 asp.net core 2.0 web api 基础框架 (3)

    Github源码地址:https://github.com/solenovex/Building-asp.net-core-2-web-api-starter-template-from-scratc ...

  4. 从头编写 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的相 ...

  5. 【转载】从头编写 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的相 ...

  6. 使用 ASP.NET Core MVC 创建 Web API(四)

    使用 ASP.NET Core MVC 创建 Web API 使用 ASP.NET Core MVC 创建 Web API(一) 使用 ASP.NET Core MVC 创建 Web API(二) 使 ...

  7. 从零开始学习 asp.net core 2.1 web api 后端api基础框架(二)-创建项目

    原文:从零开始学习 asp.net core 2.1 web api 后端api基础框架(二)-创建项目 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.ne ...

  8. 【ASP.NET Core学习】Web API

    这里介绍在ASP.NET Core中使用Web API创建 RESTful 服务,本文使用VSCode + NET Core3.0 创建简单Rest API 格式化输出 JSON Patch请求 Op ...

  9. 如何利用Serilog的RequestLogging来精简ASP.NET Core的日志输出

    这是该系列的第一篇文章:在ASP.NET Core 3.0中使用Serilog.AspNetCore. 第1部分-使用Serilog RequestLogging来简化ASP.NET Core的日志输 ...

随机推荐

  1. T-SQL Part IV: ORDER BY

    ORDER BY 返回一个Cursor,并不返回结果集.而试图将Cursor作为输入将产生了错误. 所以,下列的SQL语句将产生错误: SELECT VerID, IsComplete VerID, ...

  2. 020.掌握Pod-Pod基础使用

    一 Pod定义详解 1.1 完整Pod定义文件 apiVersion: v1 #必选,版本号,例如v1,版本号必须可以用 kubectl api-versions 查询到 kind: Pod #必选, ...

  3. hdu 1087 Super Jumping! Jumping! Jumping!(动态规划DP)

    Super Jumping! Jumping! Jumping!Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 ...

  4. PHP创建对象的6种方式

    创建对象实例: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 ...

  5. Python 编程语言要掌握的技能之一:使用数字与字符串的技巧

    最佳实践 1. 少写数字字面量 “数字字面量(integer literal)” 是指那些直接出现在代码里的数字.它们分布在代码里的各个角落,比如代码 del users[0] 里的 0 就是一个数字 ...

  6. 性能测试:深入理解线程数,并发量,TPS,看这一篇就够了

    并发数,线程数,吞吐量,每秒事务数(TPS)都是性能测试领域非常关键的数据和指标. 那么他们之间究竟是怎样的一个对应关系和内在联系? 测试时,我们经常容易将线程数等同于表述为并发数,这一表述正确吗? ...

  7. python线程条件变量Condition(31)

    对于线程与线程之间的交互我们在前面的文章已经介绍了 python 互斥锁Lock / python事件Event , 今天继续介绍一种线程交互方式 – 线程条件变量Condition. 一.线程条件变 ...

  8. matlab-汉字unicode编码转换

    str='黑大哥'bianma=unicode2native(str); disp(bianma); pp=native2unicode(bianma);disp(pp)

  9. 使用 buildx 构建多平台 Docker 镜像

    原文链接:使用 buildx 构建多平台 Docker 镜像 在工作和生活中,我们可能经常需要将某个程序跑在不同的 CPU 架构上,比如让某些不可描述的软件运行在树莓派或嵌入式路由器设备上.特别是 D ...

  10. 关于vue中的videoPlayer的src视频地址参数动态修改(网上一堆错误方法,被误导很久,自己找到了正确的方法,供大家借鉴)

    方法很简单:相信大家的问题应该是改变src的值吧,动态赋值这一步简单.this.playerOptions['sources'][0]['src'] 就是这一步解决提取src问题,主要部分用绿色框起来 ...