我正在构建一个 Asp.Net Core 2.2 Razor Pages 应用程序。我正在编写一个全局异常处理以避免在许多地方出现 try catch 块。我关注了文章 -异常处理参考这是演示解决方案链接这是我的代码,在Startup.cs中if(env.IsDevelopment()){ //app.UseDeveloperExceptionPage(new DeveloperExceptionPageOptions { // SourceCodeLineCount = 2 //}); //app.UseDatabaseErrorPage(); app.UseExceptionHandler("/Error"); app.UseStatusCodePagesWithReExecute("/Error/{0}"); app.UseExceptionMiddleware();} else {...}在ExceptionMiddleware.cs中public ExceptionMiddleware(RequestDelegate next,IMailService emailSender){ _next = next; _emailSender = emailSender;}public async Task InvokeAsync(HttpContext context){ try { await _next(context); } catch(Exception ex) { EmailException(context,ex); }}private async void EmailException(HttpContext context,Exception ex){ var uaString = context.Request.Headers["User-Agent"].ToString(); var ipAnonymizedString = context.Connection.RemoteIpAddress.AnonymizeIP(); var userId = "Unknown"; var profileId = "Unknown"; if(context.User.Identity.IsAuthenticated) { userId = context.User.FindFirstValue(ClaimTypes.NameIdentifier); profileId = context.User.GetUserClaim(ClaimsKey.ProfileId); } var sb = new StringBuilder($"An error has occurred on {context.Request.Host}. \r\n \r\n"); sb.Append($"Path = {context.Request.Path} \r\n \r\n"); sb.Append($"Error Message = {ex.Message} \r\n"); sb.Append($"Error Source = {ex.Source} - {profileId} \r\n"); if(ex.InnerException != null) { sb.Append($"Inner Exception = {ex.InnerException.ToString()} \r\n"); } else { sb.Append("Inner Exception = null \r\n"); } sb.Append($"Error StackTrace = {ex.StackTrace} \r\n"); await _emailSender.SendMasterEmailAsync($"Error on {context.Request.Host}.",sb.ToString(),uaString,ipAnonymizedString,userId); throw ex;}
目前暂无任何回答
- 0 回答
- 0 关注
- 107 浏览
添加回答
举报
0/150
提交
取消