用处:写一个过滤器,调用action方法时,将详细信息记录到数据库的log表中。
using Microsoft.AspNetCore.Mvc.Filters;
namespace WeCharGroupTest.Untities
{
public class ApiLogFilter : IAsyncActionFilter
{
private readonly ILogger _logger;
public ApiLogFilter(ILogger<ApiLogFilter> logger)
{
_logger = logger;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
//S_LOG_INFO s_Log_Info = new S_LOG_INFO();//首先定义一个log表,是为了将历史记录写入数据库中
//请求人
foreach (var item in context.HttpContext.Request.Headers)
{
//s_Log_Info.ERROR_DRI += item.Key + ":"+ item.Value+"; ";
if (item.Key.Equals("Operator"))
s_Log_Info.C_EMP_NO = item.Value.ToString();
if (item.Key.Equals("X-Real-IP"))
s_Log_Info.CLIENT_IP = item.Value.ToString();
if (item.Key.Equals("Menu_id"))
s_Log_Info.MENU_ID = item.Value.ToString();
}
//请求参数
object a = context.ActionArguments.ToJson();
var resultContext = await next();
try
{
s_Log_Info.REQUEST_HOST = resultContext.HttpContext.Request.Host.ToString();//程序所在的服务器ip+端口号
s_Log_Info.REQUEST_PATH = resultContext.HttpContext.Request.Path;//请求的地址,例/api/itms_05_api_Cosmetic_19_Risk_Check_Dashboard/Send_Risk_Check_New_Model_Email_S0519
s_Log_Info.REQUEST_METHOD = resultContext.HttpContext.Request.Method;//请求方法,例POST
}
catch (System.Exception)
{
s_Log_Info.ERROR = resultContext.Exception.Message.ToString();
s_Log_Info.ERROR_MSG = resultContext.Exception.StackTrace.ToString();
}
finally
{
List<S_LOG_INFO> list = new()
{
s_Log_Info
};
//调用bll层,写入数据库的log表中
itms_01_Bll_Common_01_System.M_s_log_info(list);
}
}
}
}
其中,上面的ToJSon是一个自定义的扩展方法
public static class ObjectExtensions
{
/// <summary>
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJson(this object obj)
{
var serializerSettings = new JsonSerializerSettings
{
DateFormatString = "yyyy-MM-dd HH:mm:ss",
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
return JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.None, serializerSettings);
}
}