.NET 6 API + Middleware + Audit rail

Request相关的参数。 需要在Program.cs 注入IHttpContextAccessor

 //Below services used to get tokenservices.AddHttpContextAccessor();services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
public string GetClientIpAddress(){var clientIp = _httpContextAccessor?.HttpContext?.Connection?.RemoteIpAddress?.ToString();return clientIp!;}public string GetBrowserInfo(){var browserInfo = _httpContextAccessor?.HttpContext?.Request?.Headers["User-Agent"].ToString();return string.IsNullOrEmpty(browserInfo) ? string.Empty : browserInfo;}public string GetMethodName(){var url = _httpContextAccessor?.HttpContext?.Request.Path;return string.IsNullOrEmpty(url) ? string.Empty : url;}public string GetParametersInfo(){var parameter = string.Empty;try{var request = _httpContextAccessor?.HttpContext?.Request;if (request != null){var methond = request.Method;Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();if (methond == "GET"){if (request.Query != null && request.Query.Count() > 0){foreach (var item in request.Query){keyValuePairs.Add(item.Key, item.Value);}parameter = JsonConvert.SerializeObject(keyValuePairs);}}else{if (request.HasFormContentType){//For Upload documentsif (request.Form.Keys != null){foreach (var itemFormKey in request.Form.Keys){keyValuePairs.Add(itemFormKey, request.Form[itemFormKey]);}}if (request.Form.Files != null && request.Form.Files.Count() > 0){keyValuePairs.Add($"Attachments-{Guid.NewGuid()}", string.Join("; ", request.Form.Files.Select(x => x.FileName)));}parameter = JsonConvert.SerializeObject(keyValuePairs);}else if (request.Query != null && request.Query.Count() > 0){foreach (var item in request.Query){keyValuePairs.Add(item.Key, item.Value);}parameter = JsonConvert.SerializeObject(keyValuePairs);}if (request.HasJsonContentType()){var rawMessage = GetRawBodyAsync(request).Result;parameter += rawMessage;}}}}catch (Exception ex){parameter = ex.Message;Log.Error(ex, $"GetParametersInfo failed. {ex.Message}");}return parameter;}

Create GlobalRequestHandlingMiddleware

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System.Net;
using Microsoft.AspNetCore.Builder;
using Newtonsoft.Json.Serialization;
using NotImplementedException = System.NotImplementedException;
using UnauthorizedAccessException = System.UnauthorizedAccessException;
using KeyNotFoundException = System.Collections.Generic.KeyNotFoundException;
using Serilog;
using System.Diagnostics;/// <summary>/// Web API Audit Trail and Exception Result handler/// </summary>public class GlobalRequestHandlingMiddleware{private readonly RequestDelegate _next;private readonly IAuditTrailManager _auditTrailManager;public GlobalRequestHandlingMiddleware(RequestDelegate next, IAuditTrailManager auditTrailManager){_next = next;_auditTrailManager = auditTrailManager ?? throw new ArgumentNullException(nameof(auditTrailManager));}public async Task Invoke(HttpContext context){Stopwatch stopwatch = new();stopwatch.Start();try{auditTrailLogDto auditInfo = _auditTrailManager.GenerateWebAPIAuditTrailLogWithoutSaveToDb();await _next(context);stopwatch.Stop();auditInfo.ExecutionDuration = (int)stopwatch.ElapsedMilliseconds;_auditTrailManager.InsertWebAPIAuditTrailLogs(auditInfo);}catch (Exception ex){await HandleExceptionAsync(context, ex, stopwatch);}}private Task HandleExceptionAsync(HttpContext context, Exception exception, Stopwatch stopwatch){/**//GenerateWebAPIAuditTrailLogWithoutSaveToDbvar auditInfo = new AbpAuditLogDto{ServiceName = serviceName,//_httpContextAccessor?.HttpContext?.Request.PathClientIpAddress = GetClientIpAddress(),BrowserInfo = GetBrowserInfo(),Parameters = GetParametersInfo(),MethodName = GetMethodName(),ExecutionTime = DateTime.UtcNow,};*/AuditTrailLogDto auditInfo = _auditTrailManager.GenerateWebAPIAuditTrailLogWithoutSaveToDb();//generate audittrailHttpStatusCode status = HttpStatusCode.BadRequest;var stackTrace = exception.StackTrace;string message = string.Empty;Guid errorCode = Guid.NewGuid();var exceptionType = exception.GetType();if (exceptionType == typeof(UserFriendlyException)){var userException = (exception as UserFriendlyException);status = userException?.Code ?? HttpStatusCode.BadRequest;message = userException?.Details ?? exception.Message;}else if (exceptionType == typeof(BadRequestException)){message = exception.Message;status = HttpStatusCode.BadRequest;}else if (exceptionType == typeof(NotFoundException) || exceptionType == typeof(KeyNotFoundException)){message = exception.Message;status = HttpStatusCode.NotFound;stackTrace = exception.StackTrace;}else if (exceptionType == typeof(NotImplementedException)){status = HttpStatusCode.NotImplemented;message = exception.Message;}else if (exceptionType == typeof(UnauthorizedAccessException)){status = HttpStatusCode.Unauthorized;message = exception.Message;}else{status = HttpStatusCode.InternalServerError;message = exception.Message;stackTrace = exception.StackTrace;}Log.Error(exception, $"ServiceName: {auditInfo.ServiceName}. Status Code: {status},message: {message}.");GlobalExceptionResponse exceptionResponseBase = new(){Success = false,Error = new(){Message = message,Code = (int)status,Details = message,StackTrace = stackTrace,Id = errorCode,DateTime = DateTime.UtcNow}};stopwatch.Stop();auditInfo.Exception = $"Status Code: {status},message: {message}. Details: {exception}";auditInfo.ExecutionDuration = (int)stopwatch.ElapsedMilliseconds;_auditTrailManager.InsertWebAPIAuditTrailLogs(auditInfo);//save to dbvar exceptionResult = JsonConvert.SerializeObject(exceptionResponseBase, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });context.Response.ContentType = HttpHeaderConstant.RESPONSE_HEADER_APPLICATION_JSON;context.Response.StatusCode = (int)status;Log.Error(exception, $"ServiceName: {auditInfo.ServiceName}. Status Code: {status},message: {message}. User Id: {auditInfo.UserId}. RemoteIpAddress: {auditInfo.ClientIpAddress}. {exceptionResult}");if (context != null){return context.Response.WriteAsync(exceptionResult);}else{return Task.FromResult(exceptionResult);}}}

 Use Middleware

    /// <summary>/// Web API Audit Trail and Exception Result handler/// </summary>public static class ApplicationBuilderExtensions{/// <summary>/// Web API Audit Trail and Exception Result handler/// </summary>/// <param name="applicationBuilder"></param>/// <returns></returns>public static IApplicationBuilder UseGlobalRequestHandling(this IApplicationBuilder applicationBuilder)=> applicationBuilder.UseMiddleware<GlobalRequestHandlingMiddleware>();}

Register in Program.cs

         //Below services used to get tokenservices.AddHttpContextAccessor();services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();services.AddSingleton<IPrincipalAccessor, PrincipalAccessor>();app.UseGlobalRequestHandling();//add Global Resust HandlingMiddleware

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/882371.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

实现对redis过期键监听案例

开发背景 为了实现当经纪人A提交分佣后如果三天后其他经纪人没有确认分佣就自动确认分佣&#xff0c;如果经纪人A修改分佣后再次提交分佣&#xff0c;时间重置为三天 实现方式 第一步&#xff1a;引入依赖 <dependency> <groupId>redis.clients</groupId> …

aardio 中最重要的控件:自定义控件使用指南

aardio虽然是个小众编程语言&#xff0c;但其在windows下做个小软件生成exe文件&#xff0c;确实方便。只是这个编程语言的生态圈小&#xff0c;文档的详细程度也完全无法和大的编程语言相提并论。今天介绍一下&#xff0c;aardio中的自定义控件如何使用。 这里我们只介绍如何做…

华为高频手撕冲刺

简单题 两数之和 方法一&#xff0c;暴力破解&#xff0c;时间复杂度O(n^2)&#xff0c;空间复杂度O(1) class Solution:def twoSum(self, nums: List[int], target: int) -> List[int]:nlen(nums)for i in range(n):for j in range(i1,n):if nums[i]nums[j]target:retur…

python 作业1

任务1: python为主的工作是很少的 学习的python的优势在于制作工具&#xff0c;制作合适的工具可以提高我们在工作中的工作效率的工具 提高我们的竞争优势。 任务2: 不换行 换行 任务3: 安装pycharm 进入相应网站Download PyCharm: The Python IDE for data science and we…

AnaTraf | TCP重传的工作原理与优化方法

目录 什么是TCP重传&#xff1f; TCP重传的常见触发原因 TCP重传对网络性能的影响 1. 高延迟与重传 2. 吞吐量的下降 如何优化和减少TCP重传 1. 优化网络设备配置 2. 优化网络链路 3. 网络带宽的合理规划 4. 部署CDN和缓存策略 结语 AnaTraf 网络性能监控系统NPM | …

餐饮店怎么标注地图位置信息?

随着市场竞争的日益激烈&#xff0c;商家若想在竞争中脱颖而出&#xff0c;就必须想方设法去提高自身的曝光度和知名度&#xff0c;为店铺带来更多的客流量。其中&#xff0c;地图标注便是一种简单却极为有效的方法。通过在地图平台上添加店铺位置信息&#xff0c;不仅可以方便…

Unity3D 框架如何实现道路引导 UV 动画详解

Unity3D 是一款功能强大的游戏引擎&#xff0c;能够实现各种各样的游戏效果。在游戏开发中&#xff0c;道路引导是一个常见的需求&#xff0c;可以用来指引玩家前进的方向。而为了增加游戏的真实感和视觉效果&#xff0c;我们可以使用道路引导 UV 动画来模拟道路的移动效果。本…

Qt-系统文件相关介绍使用(61)

目录 描述 输⼊输出设备类 打开/读/写/关闭 使用 先初始化&#xff0c;创建出大致的样貌 输入框设置 绑定槽函数 保存文件 打开文件 提取文件属性 描述 在C/C Linux 中我们都接触过关于文件的操作&#xff0c;当然 Qt 也会有对应的文件操作的 ⽂件操作是应⽤程序必不…

两阶段提交(2PC)如何保证一致性

事务的两阶段提交&#xff08;2PC, Two-Phase Commit&#xff09;是一种分布式事务协议&#xff0c;用于确保多个参与者&#xff08;例如多个数据库或服务&#xff09;在分布式系统中一致地提交或回滚事务。它分为两个阶段&#xff1a;准备阶段&#xff08;Prepare Phase&#…

思科网络设备命令

一、交换机巡检命令 接口和流量状态 show interface stats&#xff1a;查看所有接口当前流量。show interface summary&#xff1a;查看所有接口当前状态和流量。show interface status&#xff1a;查看接口状态及可能的错误。show interface | include errors | FastEthernet …

【C语言】文件操作(1)(文件打开关闭和顺序读写函数的万字笔记)

文章目录 一、什么是文件1.程序文件2.数据文件 二、数据文件1.文件名2.数据文件的分类文本文件二进制文件 三、文件的打开和关闭1.流和标准流流标准流 2.文件指针3.文件的打开和关闭文件的打开文件的关闭 四、文件的顺序读写1.fgetc函数2.fputc函数3.fgets函数4.fputs函数5.fsc…

微信小程序上传组件封装uploadHelper2.0使用整理

一、uploadHelper2.0使用步骤说明 uploadHelper.js ---上传代码封装库 cos-wx-sdk-v5.min.js---腾讯云&#xff0c;对象存储封装库 第一步&#xff0c;下载组件代码&#xff0c;放置到自己的小程序项目中 第二步、 创建上传对象&#xff0c;执行选择图片/视频 var _this th…

npm install进度卡在 idealTree:node_global: sill idealTree buildDeps

ping一下源&#xff1a;ping http://registry.npm.taobao.org/ ping不通&#xff0c;原因&#xff1a;原淘宝npm永久停止服务&#xff0c;已更新新域名~~震惊&#xff01;&#xff01;&#xff01; 重新安装&#xff1a;npm config set registry https://registry.npmmirror.c…

推荐?还是踩雷?3款中英互译软件大盘点,你真的选对了吗?

作为一个爱到处跑的人&#xff0c;我特别明白旅行的时候能说会道有多重要。不管是跟当地人聊天&#xff0c;还是看路标、菜单&#xff0c;有个好用的翻译软件是肯定少不了的。今天&#xff0c;我打算给你们介绍3款中英文互译的翻译工具&#xff0c;帮你挑出最适合自己的那一个。…

机器学习:opencv--人脸检测以及微笑检测

目录 前言 一、人脸检测的原理 1.特征提取 2.分类器 二、代码实现 1.图片预处理 2.加载分类器 3.进行人脸识别 4.标注人脸及显示 三、微笑检测 前言 人脸检测是计算机视觉中的一个重要任务&#xff0c;旨在自动识别图像或视频中的人脸。它可以用于多种应用&#xff0…

Python和MATLAB锂电铅蓄电化学微分模型和等效电路

&#x1f3af;要点 对比三种电化学颗粒模型&#xff1a;电化学的锂离子电池模型、单粒子模型和带电解质的单粒子模型。求解粒子域内边界通量与局部电流密度有关的扩散方程。扩展为两个相的负或正电极复合电极粒子模型。模拟四种耦合机制下活性物质损失情况。模拟锂离子电池三参…

【PhpSpreadsheet】ThinkPHP5+PhpSpreadsheet实现批量导出数据

目录 前言 一、安装 二、API使用 三、完整实例 四、效果图 前言 为什么使用PhpSpreadsheet&#xff1f; 由于PHPExcel不再维护&#xff0c;所以建议使用PhpSpreadsheet来导出exlcel&#xff0c;但是PhpSpreadsheet由于是个新的类库&#xff0c;所以只支持PHP7.1及以上的版…

服务器数据恢复—RAID5阵列上层Linux操作系统中节点损坏的数据恢复案例

服务器数据恢复环境&#xff1a; 一台服务器上有一组由5块硬盘&#xff08;4块数据盘1块热备盘&#xff09;组建的raid5阵列。服务器安装Linux Redhat操作系统&#xff0c;运行一套基于oracle数据库的OA系统。 服务器故障&#xff1a; 这组raid5阵列中一块磁盘离线&#xff0c…

观测云 AI 助手上线:智能运维,从此触手可及!

在当前的云原生时代&#xff0c;运维的复杂性和数据的爆炸式增长给企业带来了前所未有的挑战。为了帮助企业高效应对这些挑战&#xff0c;观测云自豪地推出了 AI 助手——智能化的运维助手&#xff0c;让每位用户都能轻松驾驭复杂的可观测性场景。 01 你身边的 PE 助手&#x…

《重置MobaXterm密码并连接Linux虚拟机的完整操作指南》

目录 引言 一、双击MobaXterm_Personal_24.2进入&#xff0c;但是忘记密码。 那么接下来请跟着我操作。 二、点击此链接&#xff0c;重设密码。 三、下载完成后&#xff0c;现在把这个exe文件解压。注意解压要与MobaXterm_Personal_24.2.exe在同一目录下哦&#xff0c;不然…