為了實現自己的操作日志記錄功能,我有個思路:
- 自定義特性ActionAttribute;
- 在每個控制器方法上加上自定義特性;
- 通過中間件,在每個控制器方法執行完后,獲取該特性信息,寫入數據庫;
首先,自定義特性ActionAttribute.cs
public class ActionAttribute : Attribute
{
public string ActionName { get; set; }
public ActionAttribute(string actionName)
{
ActionName = actionName;
}
}
自定義中間件類:ActionLogMiddleware.cs
public class ActionLogMiddleware
{
private readonly RequestDelegate _next;
private readonly ActionLogService _service;
public ActionLogMiddleware(RequestDelegate next, ActionLogService actionLogService)
{
_next = next;
_service = actionLogService;
}
public async Task InvokeAsync(HttpContext context)
{
var endpoint = GetEndpoint(context);
var username = "未知用戶";
if (endpoint != null)
{
var actionAttribute = endpoint.Metadata.GetMetadata<ActionAttribute>();
if (actionAttribute != null)
{
var actionName = actionAttribute.ActionName;
ActionLog log = new ActionLog
{
Action = actionName,
ActionTime = DateTime.Now,
Username = username,
IP = ip,
};
await _service.Add(log);
}
}
await _next(context);
}
public static Endpoint GetEndpoint(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
return context.Features.Get<IEndpointFeature>()?.Endpoint;
}
}
擴展方法,方便激活自定義中間件:ActionLogMiddlewareExtensions.cs
public static class ActionLogMiddlewareExtensions
{
public static IApplicationBuilder UseActionLog(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<ActionLogMiddleware>();
}
}
最后,在Startup.cs中激活自定義中間件
app.UseActionLog();
使用方法,在控制器的各個方法上加上【ActionAttribute】
[Action("刪除公告")]
public async Task<ActionResult<int>> Delete(int id)
{
var model = await _service.GetById(id);
if (model == null)
{
return NotFound();
}
return await _service.Delete(model);
}