123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- using Aspose.Words;
- using NPOI.HSSF.Record;
- using OASystem.Domain.Attributes;
- using OASystem.Domain.Entities.Customer;
- using OASystem.Infrastructure.Repositories.CRM;
- using System.ComponentModel.DataAnnotations;
- using System.Diagnostics;
- using XAct;
- using static Google.Protobuf.Reflection.SourceCodeInfo.Types;
- namespace OASystem.API.Middlewares
- {
- /// <summary>
- /// 指定API操作记录信息
- /// </summary>
- public class RecordAPIOperationMiddleware
- {
- private readonly RequestDelegate _next;
- private readonly HttpClient _httpClient;
- private readonly IConfiguration _config;
- private readonly SqlSugarClient _sqlSugar;
- public RecordAPIOperationMiddleware(RequestDelegate next, IConfiguration config, HttpClient httpClient, SqlSugarClient sqlSugar)
- {
- _next = next;
- _httpClient = httpClient;
- _config = config;
- _sqlSugar = sqlSugar;
- }
- public async Task InvokeAsync(HttpContext context)
- {
- // 启用请求体流的缓冲,允许多次读取
- context.Request.EnableBuffering();
- // 读取请求体内容
- var requestBodyText = await ReadRequestBody(context.Request);
- // 检查控制器方法是否使用了自定义属性
- var endpoint = context.GetEndpoint();
- var apiLogAttribute = endpoint?.Metadata?.GetMetadata<ApiLogAttribute>();
- if (apiLogAttribute != null)
- {
- var startTime = DateTime.UtcNow;
- // 保存原始响应体流
- var originalResponseBody = context.Response.Body;
- // 创建一个新的内存流来捕获响应体
- using var responseMemoryStream = new MemoryStream();
- context.Response.Body = responseMemoryStream;
- // 调用下一个中间件
- await _next(context);
- // 读取响应体内容
- var responseBodyText = await new StreamReader(responseMemoryStream).ReadToEndAsync();
- // 重置响应体流的位置
- responseMemoryStream.Position = 0;
- // 将响应体内容写回原始响应体流
- await responseMemoryStream.CopyToAsync(originalResponseBody);
- // 记录请求结束时间
- var endTime = DateTime.UtcNow;
- // 计算耗时
- var duration = (long)(endTime - startTime).TotalMilliseconds;
- int portType = 1;
- var logInfo = new Crm_TableOperationRecord() {
- TableName = apiLogAttribute.TableName,
- PortType = portType,
- OperationItem = apiLogAttribute.OperationEnum,
- DataId = apiLogAttribute.DataId,
- RequestUrl = context.Request.Path,
- RequestParam = requestBodyText,
- ReturnResult = responseBodyText,
- Elapsed = duration,
- Status = context.Response.StatusCode.ToString(),
- };
- // 存储到数据库
- await _sqlSugar.Insertable(logInfo).ExecuteCommandAsync();
- }
- else
- {
- // 调用下一个中间件
- await _next(context);
- }
- }
- private async Task<string> ReadRequestBody(HttpRequest request)
- {
- request.EnableBuffering();
- // 读取请求体内容
- using var reader = new StreamReader(request.Body, Encoding.UTF8, true, 1024, true);
- var requestBodyText = await reader.ReadToEndAsync();
- // 重置请求体流的位置
- request.Body.Position = 0;
- return requestBodyText;
- }
- private async Task<string> GetExternalIp()
- {
- var response = await _httpClient.GetAsync("https://ifconfig.me");
- response.EnsureSuccessStatusCode();
- return await response.Content.ReadAsStringAsync();
- }
- private async Task<string> GetIpLocation(string ip)
- {
- var response = await _httpClient.GetAsync($"https://ipinfo.io/{ip}/json");
- response.EnsureSuccessStatusCode();
- var json = await response.Content.ReadAsStringAsync();
- var ipInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
- return $"{ipInfo.country}, {ipInfo.city}";
- }
-
- }
- }
|