我使用ServiceFilter
创建了UserActivity Logging或Audit跟踪。我无法使用动作过滤器,因为我需要传递依赖项。
我成功记录了用户的活动。
public class ActivityLog : ActionFilterAttribute
{
private ILogUserActivityService _service;
//injecting specified service to insert the log in database.
public ActivityLog(ILogUserActivityService service)
{
_service = service;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Stores the Request in an Accessible object
var request = filterContext.HttpContext.Request;
// Generate the log of user activity
LogUserActivity log = new LogUserActivity()
{
// Username. shall be changed to UserId later afteter Auth management.
UserName = filterContext.HttpContext.User.Identity.Name ?? "Anonymous",
// The IP Address of the Request
IpAddress = request.HttpContext.Connection.RemoteIpAddress.ToString(),
// The URL that was accessed
AreaAccessed = Microsoft.AspNetCore.Http.Extensions.UriHelper.GetDisplayUrl(request),
// Creates Timestamp
TimeStamp = DateTime.Now
};
//saves the log to database
_service.SaveLog(log);
// Finishes executing the Action as normal
base.OnActionExecuting(filterContext);
}
}
我可以在控制器上方添加[ServiceFilter(typeof(ActivityLog))]
,这非常有效。
数据库记录:
但现在我想补充更多信息。我将添加另一个名为“Description”的列,我将能够输入有关用户删除的内容,他所做的更改,添加了什么(以及少数属性)等的描述。
我期待Serilog中有Log.information(...)
之类的东西。那我怎么能实现这样的呢?