public async Task Invoke(HttpContext httpContext) { try { await _next(httpContext); } catch (Exception ex) { LogHelper.Logger.Fatal(ex, $"【异常信息】:{ex.Message} 【请求路径】:{httpContext.Request.Method}:{httpContext.Request.Path}\n " + $"【UserHostAddress】:{ LionWeb.GetClientIp()} " + $"【UserAgent】:{ httpContext.Request.Headers["User-Agent"]}"); if (ex is CustomSystemException se) { await ExceptionResult(httpContext, new ResponseModel().Fail(se.Code, se.Message, "").ToJson(true, isLowCase: true)); } else if (ex is DataValidException de) { await ExceptionResult(httpContext, new ResponseModel().Fail(de.Code, de.Message, "").ToJson(true, isLowCase: true)); } else { #if DEBUG Console.WriteLine(ex); var content = ex.Message; #else var content = "系统错误,请稍后再试或联系管理人员。"; #endif await ExceptionResult(httpContext, new ResponseModel().Fail(ResponseCode.UnknownEx, content, "").ToJson(true, isLowCase: true)); } } }
public override void OnActionExecuting(ActionExecutingContext context) { #if DEBUG LogHelper.Logger.Debug( "[Ip]:{0}\n [Arguments]:{1}\n [Headers]:{2}\n ", LionWeb.GetClientIp(), context.ActionArguments.ToJson(true), context.HttpContext.Request.Headers.ToJson(true) ); _stopWatch = new Stopwatch(); _stopWatch.Start(); #endif base.OnActionExecuting(context); }
public override void OnException(ExceptionContext filterContext) { if (filterContext.ExceptionHandled) { return; } var controllerName = (string)filterContext.RouteData.Values["controller"]; var actionName = (string)filterContext.RouteData.Values["action"]; var request = filterContext.HttpContext.Request; LogHelper.Logger.Fatal(filterContext.Exception, $"【异常信息】:{filterContext.Exception.Message} 【请求路径】:{request.Method}:{request.Path}\n " + $"【Controller】:{controllerName} - 【Action】:{actionName}\n " + $"【UserHostAddress】:{ LionWeb.GetClientIp()} " + $"【UserAgent】:{ request.Headers["User-Agent"]}"); if (filterContext.Exception is CustomSystemException se) { filterContext.Result = new CustomHttpStatusCodeResult(200, se.Code, se.Message); } else if (filterContext.Exception is DataValidException de) { filterContext.Result = new CustomHttpStatusCodeResult(200, de.Code, de.Message); } else { var content = ""; #if DEBUG Console.WriteLine(filterContext.Exception); content = filterContext.Exception.Message; #else content = "系统错误,请稍后再试或联系管理人员。"; #endif filterContext.Result = new CustomHttpStatusCodeResult(200, ResponseCode.UnknownEx, content); } filterContext.ExceptionHandled = true; // 处理完异常之后,请记得将此属性更改为true,表明已经处理过了。将不会 // 处理范围仅限于MVC中间件,若要捕捉MVC中间件之前的异常, // 请使用ExceptionHandlerMiddleware中间件来处理,因为在管道中放置在第一个位置 }
/// <summary> /// 自定义的错误拦截管道来作为处理程序 /// </summary> /// <param name="httpContext"></param> /// <param name="next"></param> /// <returns></returns> private async Task CustomExceptionHandler(HttpContext httpContext, Func <Task> next) { //该信息由ExceptionHandlerMiddleware中间件提供,里面包含了ExceptionHandlerMiddleware中间件捕获到的异常信息。 var exceptionDetails = httpContext.Features.Get <IExceptionHandlerFeature>(); var ex = exceptionDetails?.Error; if (ex != null) { LogHelper.Logger.Fatal(ex, $"【异常信息】:{ex.Message} 【请求路径】:{httpContext.Request.Method}:{httpContext.Request.Path}\n " + $"【UserHostAddress】:{LionWeb.GetClientIp()} " + $"【UserAgent】:{httpContext.Request.Headers["User-Agent"]}"); if (ex is CustomSystemException se) { await ExceptionResult(httpContext, new ResponseModel().Fail(se.Code, se.Message, "").ToJson(true, isLowCase: true)); } else if (ex is DataValidException de) { await ExceptionResult(httpContext, new ResponseModel().Fail(de.Code, de.Message, "").ToJson(true, isLowCase: true)); } else { #if DEBUG Console.WriteLine(ex); var content = ex.Message; #else var content = "系统错误,请稍后再试或联系管理人员。"; #endif await ExceptionResult(httpContext, new ResponseModel().Fail(ResponseCode.UnknownEx, content, "").ToJson(true, isLowCase: true)); } } }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IMemoryCache memoryCache, IHostApplicationLifetime applicationLeftTime) { // 全局异常处理的三种方式 // 1.自定义的异常拦截管道 - - 放在第一位处理全局未捕捉的异常 app.UseExceptionHandler(build => build.Use(CustomExceptionHandler)); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); app.UseHttpsRedirection(); // 从 http 跳转到 https Config_HealthChecks(app); //测试情况下不开启健康检查 } // 2.使用自定义异常处理中间件 处理该中间件以后未捕捉的异常 //app.UseMiddleware<CustomExceptionMiddleware>(); //autofac 新增 LionWeb.AutofacContainer = app.ApplicationServices.CreateScope().ServiceProvider.GetAutofacRoot(); // Z.EntityFramework.Extensions 扩展包需要 --无法显示日志 using (var container = LionWeb.AutofacContainer.BeginLifetimeScope()) { EntityFrameworkManager.ContextFactory = context => container.Resolve <LionDbContext>(); LionWeb.Configure(container.Resolve <IHttpContextAccessor>()); } LionWeb.Environment = env; LionWeb.MemoryCache = memoryCache; app.UseStaticFiles(); //app.UseCookiePolicy(); Config_Swagger(app); app.UseRouting(); //app.UseRequestLocalization(); // 跨域 app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().WithMethods(new string[] { HttpMethods.Get, HttpMethods.Post, HttpMethods.Delete, HttpMethods.Put })); // app.UseSession(); // app.UseResponseCaching(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapGet("/", async context => { context.Response.ContentType = "text/html; charset=utf-8"; await context.Response.WriteAsync("<div style='text-align: center;margin-top: 15%;'><h3>项目<b style='color: green;'>启动成功</b>,测试请使用接口测试工具,或与前端联调!</h3> <h4>项目<a href='/apidoc' style='color: cornflowerblue;'>接口文档</a>,点击查看</h4></div>"); }); }); // 初始化 Init(); applicationLeftTime.ApplicationStopping.Register(OnShutdown, app); }