You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.9 KiB
C#

8 months ago
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NPin.Framework.Core.Extensions;
using NPin.Framework.Upms.Domain.Shared.OperLog;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Users;
namespace NPin.Framework.Upms.Domain.OperLog;
public class OperLogGlobalAttribute : ActionFilterAttribute, ITransientDependency
{
private readonly ILogger<OperLogGlobalAttribute> _logger;
private IRepository<OperationLogEntity> _repository;
private ICurrentUser _currentUser;
public OperLogGlobalAttribute(ILogger<OperLogGlobalAttribute> logger, IRepository<OperationLogEntity> repository,
ICurrentUser currentUser)
{
_logger = logger;
_repository = repository;
_currentUser = currentUser;
}
public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
// 获取执行结果
var resultContext = await next.Invoke();
// 判断是否在 控制器方法 上
if (resultContext.ActionDescriptor is not ControllerActionDescriptor contextActionDescriptor) return;
// 查找特性
var operLogAttribute = contextActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
.FirstOrDefault(a => a.GetType() == typeof(OperLogAttribute)) as OperLogAttribute;
// 无特性表达式 直接返回 不处理
if (operLogAttribute is null) return;
// 获取Ip
var logEntity = OperationLogEntity.GetInfoByHttpContext(resultContext.HttpContext);
logEntity.OperType = operLogAttribute.OperType;
logEntity.Title = operLogAttribute.Title;
logEntity.RequestMethod = resultContext.HttpContext.Request.Method;
logEntity.Method = resultContext.HttpContext.Request.Path.Value;
logEntity.OperUser = _currentUser.UserName;
// 请求结果保存
if (operLogAttribute.IsSaveResponseData)
{
if (resultContext.Result is ContentResult { ContentType: "application/json" } result)
{
logEntity.RequestResult = result.Content?.Replace("\r\n", "").Trim();
}
if (resultContext.Result is JsonResult result2)
{
logEntity.RequestResult = result2.Value?.ToString();
}
if (resultContext.Result is ObjectResult result3)
{
logEntity.RequestResult = JsonConvert.SerializeObject(result3);
}
}
// 请求参数保存
if (operLogAttribute.IsSaveRequestData)
{
// 不建议保存 比较吃性能
// logEntity.RequestParam = context.HttpContext.GetRequestValue();
}
await _repository.InsertAsync(logEntity);
}
}