How to implement a LOG of updates with ASP.NET MVC?

5

I would like ideas on how to implement a generic update LOG in DB (Entity Framework 6+) that would allow me to discover information such as: System user X on date Y changed name and date of birth (from, to) in the customer registry.

I think it's possible to implement something like this generically, without having to create the log entries for each action in each controller, using ActionFilter and / or EntityFramework Interceptor.

    
asked by anonymous 16.06.2014 / 14:03

1 answer

6

Step 1. Create a Model to register actions

namespace SeuProjeto.Models 
{
    public class ActionsLog 
    {
        [Key]
        public Guid ActionsLogId { get; set; }
        public String Controller { get; set; }
        public String Action { get; set; }
        public String Ip { get; set; }
        public DateTime DateAndTime { get; set; }
        // Coloque aqui os campos extras que deseja usar para o registro
    }
}

Step 2. Implement a Filter derived from ActionFilter

namespace SeuProjeto.Filters 
{
    public class CustomActionFilter : ActionFilterAttribute, IActionFilter
    {
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Coloque aqui algumas regras de negócio que quiser antes de fazer o log.

            // Aqui é o registro propriamente dito
            var contexto = new MeuProjetoContext();

            var log = new ActionsLog()
            {
                ActionsLogId = Guid.NewGuid(),
                Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                Action = filterContext.ActionDescriptor.ActionName + " (Logged By: Custom Action Filter)",
                Ip = filterContext.HttpContext.Request.UserHostAddress,
                DateAndTime = filterContext.HttpContext.Timestamp
                // Coloque aqui os campos extras para inclusão
            };

            contexto.ActionsLogs.Add(log);
            contexto.SaveChanges();

            this.OnActionExecuting(filterContext);
        }
    }
}

Step 3. Record your ActionFilter in the desired% w /%

[CustomActionFilter]
public class MeuController : Controller
{
    ...
}

Or decorate the Controller individually

[CustomActionFilter]
public ActionResult Index()
{
  ...
}

[CustomActionFilter]
public ActionResult Search(string term)
{
  ...
}
    
16.06.2014 / 19:11