.NET Core通过过滤器和中间件两种方式实现全局异常捕获和日志记录
1.一共有五类过滤器IAsyncAuthorizationFilter IAsyncResourceFilter IAsyncActonFilter IAsyncExceptionFilter IAsyncResultFilter 去掉Async就是同步的
2.注册过滤器 全局注册和Attribute注册 用在特定的Action上
通过过滤器实现全局异常处理
1.建立自己的一个过滤器
public class CustomerExceptionFilter : Attribute, IExceptionFilter
{
private readonly ILogger logger = null;
private readonly IHostingEnvironment environment = null;
public CustomerExceptionFilter(ILogger<CustomerExceptionFilter> logger, IHostingEnvironment environment)
{
this.logger = logger;
this.environment = environment;
} public void OnException(ExceptionContext context)
{
Exception exception = context.Exception;
string error = string.Empty; void ReadException(Exception ex)
{
error += string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, ex.InnerException);
if (ex.InnerException != null)
{
ReadException(ex.InnerException);
}
} ReadException(context.Exception);
logger.LogError(error); ContentResult result = new ContentResult
{
StatusCode = ,
ContentType = "text/json;charset=utf-8;"
}; if (environment.IsDevelopment())
{
var json = new { message = exception.Message, detail = error };
result.Content = JsonConvert.SerializeObject(json);
}
else
{
result.Content = "抱歉,出错了";
}
context.Result = result;
context.ExceptionHandled = true;
}
}
2.添加Nugut包 NLog.Extensions.Logging NLog.Web.AspNetCore ,并在 Startup.cs 文件的 Configure 方法中添加扩展
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory factory)
{
// 将 NLog
factory.AddConsole(Configuration.GetSection("Logging"))
.AddNLog()
.AddDebug(); var nlogFile = System.IO.Path.Combine(env.ContentRootPath, "nlog.config");
env.ConfigureNLog(nlogFile); if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseMvc();
}
3.日志配置文件信息
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" internalLogLevel="info"> <!-- Load the ASP.NET Core plugin -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions> <!-- Layout: https://github.com/NLog/NLog/wiki/Layout%20Renderers -->
<targets>
<target xsi:type="File" name="errorfile" fileName="/data/logs/logfilter/error-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}| ${message} ${exception}|${aspnet-Request-Url}" />
<target xsi:type="Null" name="blackhole" />
</targets> <rules>
<logger name="Microsoft.*" minlevel="Error" writeTo="blackhole" final="true" />
<logger name="*" minlevel="Error" writeTo="errorfile" />
</rules>
</nlog>
4.把这个过滤器注入到容器中
services.AddMvc(
options =>
{
options.Filters.Add(typeof(CustomerExceptionFilter));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
只要请求进入到了MVC中间件中之后抛的异常 都会进到自定义的Filter中
************************
通过中间件实现全局异常处理
1.建立一个自定义的全局异常处理中间件
public class ExceptionMiddleware
{
private readonly RequestDelegate next;
private readonly ILogger logger;
private IHostingEnvironment environment; public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger, IHostingEnvironment environment)
{
this.next = next;
this.logger = logger;
this.environment = environment;
} public async Task Invoke(HttpContext context)
{
try
{
await next.Invoke(context);
var features = context.Features;
}
catch (Exception e)
{
await HandleException(context, e);
}
} private async Task HandleException(HttpContext context, Exception e)
{
context.Response.StatusCode = ;
context.Response.ContentType = "text/json;charset=utf-8;";
string error = ""; void ReadException(Exception ex)
{
error += string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, ex.InnerException);
if (ex.InnerException != null)
{
ReadException(ex.InnerException);
}
} ReadException(e);
if (environment.IsDevelopment())
{
var json = new { message = e.Message, detail = error };
error = JsonConvert.SerializeObject(json);
}
else
error = "抱歉,出错了"; await context.Response.WriteAsync(error);
}
}
2.在管道中加入自定义中间件
app.UseMiddleware<ExceptionMiddleware>();
2.在管道中通过try catch进行异常捕获 这个中间件后面的所有代码都在 try catch里面 只要出发了异常 就会给当前中间件捕获
注意 在某个中间件中发生了异常 但是他抛出的时候 在当前中间件就处理掉了 没有继续往上抛出 这时候就捕获不到
https://www.cnblogs.com/viter/p/10013195.html
.NET Core通过过滤器和中间件两种方式实现全局异常捕获和日志记录的更多相关文章
- 七 异常处理的两种方式(创建全局异常处理器&自定义异常)
1 创建全局异常处理器 实现HandlerExceptionResolve接口 package com.springmvc01; import javax.servlet.http.HttpServl ...
- java程序中抛出异常的两种方式,及异常抛出的顺序
在java中,会经常遇到异常,java提供了两种抛出异常的方式. 方式一: throws ,抛出具体代码中的异常,这种方式编译器都会提示,举例: public static void main(Str ...
- 创建Java多线程的两种方式和线程异常
一.使用多线程的两种方法 使用多线程的两种方法有:继承Thread类和实现runable接口. 二.继承Thread类 来看一下thread类的源代码: class Thread implement ...
- 在.net core中数据操作的两种方式(Db first && Code first)
在开发过程中我们通常使用的是Db first这种模式,而在.net core 中推荐使用的却是 code first 反正我是很不习惯这种开发模式 于是就搜寻整个微软的官方文档,终于找到了有关.net ...
- EntityFramework Core 2.0自定义标量函数两种方式
前言 上一节我们讲完原始查询如何防止SQL注入问题同时并提供了几种方式.本节我们继续来讲讲EF Core 2.0中的新特性自定义标量函数. 自定义标量函数两种方式 在EF Core 2.0中我们可以将 ...
- Spring Boot配置过滤器的两种方式
过滤器(Filter)是Servlet中常用的技术,可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截,常用的场景有登录校验.权限控制.敏感词过滤等,下面介绍下Spring Boot配置过 ...
- .NET MVC中登录过滤器拦截的两种方法
今天给大家介绍两种ASP中过滤器拦截的两种方法. 一种是EF 的HtppModule,另一种则是灵活很多针对MVC的特性类 Attribute 具体什么是特性类可以参考着篇文章:https://www ...
- 国产化之 .NET Core 操作达梦数据库DM8的两种方式
背景 某个项目需要实现基础软件全部国产化,其中操作系统指定银河麒麟,数据库使用达梦V8,CPU平台的范围包括x64.龙芯.飞腾.鲲鹏等.考虑到这些基础产品对.NET的支持,最终选择了.NET Core ...
- Python 实现接口类的两种方式+邮件提醒+动态导入模块+反射(参考Django中间件源码)
实现接口类的两种方式 方式一 from abc import ABCMeta from abc import abstractmethod class BaseMessage(metaclass=AB ...
随机推荐
- Kali Hydra SSL issue, xHydra (GUI version of Hydra) works just fine
First find the source code. (https://is.gd/LlS5Sy) - Example search Once located you must download i ...
- selenium--键盘事件
from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Fi ...
- 交叉编译7zip过程
https://github.com/Distrotech/p7zip.git 从这里下载,不要从sourceforge.net上下载,那上面的缺makefile文件. 我主要把文件 makefile ...
- OO第二单元电梯线程系列总结作业
电梯系列第一次作业 功能描述: 傻瓜电梯无需考虑超载捎带 线程模式: Producer-Consumer Pattern 思路: 第一次作业是一个傻瓜电梯,分别有一个生产者生成电梯指令(也就是Inpu ...
- 关于sql server profiler 监控工具的使用
勾选以下属性: 记录这个数据库访问磁盘的次数:
- python selenium处理windows窗口
selenium本身处理不了windows窗口,需要借助,PyAutoit包 与autoit工具 这里以文件上传窗口为例: 1.安装python pyauto包 pip install PyAutoi ...
- JavaScript中创建对象的几种模式
代码如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...
- racle SQL性能优化
(1) 选择最有效率的表名顺序(只在基于规则的优化器中有效): Oracle的解析器按照从右到左的顺序处理FROM子句中的表名,FROM子句中写在最后的表(基础表 driving table)将被最先 ...
- [ABP] ASP.NET Zero 5.6.0 之 破解日志
继上次ASP.NET Zero 5.5.2的破解https://www.cnblogs.com/VAllen/p/ABP-ASP-NET-Zero-5-5-2-Crack.html之后,现在发布了AS ...
- 《CSS世界》读书笔记(十四)
<!-- <CSS世界>张鑫旭著 --> 功勋卓越的 border 属性 border-width 不支持百分比值 border-style 类型 border-style ...