您可以定義日誌實體是這樣的:
public class LogAction
{
public DateTime PerformedAt { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public string Description { get; set; }
public string UserName { get; set; }
public string Ip { get; set; }
}
然後您可以創建一個自定義屬性是這樣的:
public class LogAttribute : ActionFilterAttribute
{
public string Description { get; set; }
public IUnitOfWork Uow { get; set; }
public ILogActionService LogActionService { get; set; }
public IApplicationUserManager ApplicationUserManager { get; set; }
public LogAttribute(string desciption)
{
Description = desciption;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
string currentUserId = null;
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
currentUserId = filterContext.HttpContext.User.Identity.GetUserId();
}
var model = new LogAction
{
UserName = currentUserId ?? "Anonymouse user",
Action = filterContext.ActionDescriptor.ActionName,
Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
Description = Description,
PerformedAt = DateTime.Now,
Ip = Helper.Helper.GetUser_IP_Message()
};
LogActionService.AddLog(model);
Uow.SaveAllChanges();
base.OnActionExecuted(filterContext);
}
}
正如你所看到的,在OnActionExecuted
方法,你可以填充該實體並將其保存到數據庫中,因此您可以使用以下方式的屬性:
[Log("Home Page")]
public ActionResult Index()
{
return View();
}