mh_frame_sps/APT.API/LogAttribute.cs
2026-04-07 13:47:52 +08:00

51 lines
1.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using APT.Infrastructure.Core;
using log4net;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace APT.API
{
public class LogAttribute : Attribute, IAsyncActionFilter
{
/// <summary>
/// 添加操作日志 liyouming
/// </summary>
/// <param name="context"></param>
/// <param name="next"></param>
/// <returns></returns>
public async Task OnActionExecutionAsync(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context, ActionExecutionDelegate next)
{
string actionArguments = context.ActionArguments.ToJson();
var resultContext = await next();
string url = resultContext.HttpContext.Request.Host + resultContext.HttpContext.Request.Path + resultContext.HttpContext.Request.QueryString;
string method = resultContext.HttpContext.Request.Method;
dynamic result = resultContext.Result.GetType().Name == "EmptyResult" ? new { Value = "EmptyResult" } : resultContext.Result as dynamic;
var userHeads = resultContext.HttpContext.Request.Headers;
var userid = string.Empty;
var username = string.Empty;
if (userHeads.ContainsKey("userid"))
{
userid = userHeads["userid"].ToString();
}
if (userHeads.ContainsKey("username"))
{
username = userHeads["username"].ToString();
}
string response = JsonConvert.SerializeObject(result.Value);
var str = $"用户ID:[{userid}],姓名:[{username}],api地址[{url}],方法:[{method}],接口参数:[{actionArguments}],应答:[{response}]";
LoggerManager.GetLogger("SQLLog").Info(str);
await next.Invoke();
}
}
}