ASP.NET - 使用mvc 4过滤器将CRUD操作记录到数据库

时间:2015-04-14 14:02:40

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我想我可以在MVC 4中使用actionfilters来记录有人从数据库创建,编辑或删除行的时间。我可以记录控制器名称,操作名称,IP和身份没问题。但我也想写入数据库,已删除的整行。我还想写入数据库,对行进行的更改。我希望这个过滤器可以重用于多个控制器。

我写了一些代码,但我几乎陷入困境。

public class ActivityLog : ActionFilterAttribute, IActionFilter
    {
        private readonly DbContext1 _db = new DbContext1();

        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (!filterContext.Controller.ViewData.ModelState.IsValid) return;
            string parameters;
            var formParams = filterContext.HttpContext.Request.Form;

            switch (filterContext.ActionDescriptor.ActionName.ToUpper())
            {
                case "CREATE": //show created object in log parameters
                    parameters = "{" +
                                 String.Join(", ",
                                     formParams.Cast<string>()
                                         .Where(
                                             x =>
                                                 x != "__RequestVerificationToken" &&
                                                 !String.IsNullOrWhiteSpace(formParams[x]))
                                         .Select(x => x + ":" + formParams[x])) + "}";
                    break;
                case "EDIT": //show only changes in object in log parameters
                    parameters = JsonConvert.SerializeObject(/*dunno what to put here*/);
                    break;
                case "DELETE": //show deleted object in log parameters
                    parameters = JsonConvert.SerializeObject(/*dunno what to put here*/);
                    break;
                default:
                    return;
            }

            var log = new Models.ActivityLog()
            {
                DateTime = filterContext.HttpContext.Timestamp,
                Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                Action = filterContext.ActionDescriptor.ActionName,
                UserId = filterContext.HttpContext.User.Identity.Name,
                IP = filterContext.HttpContext.Request.UserHostAddress,
                Parameters = parameters
            };
            _db.ActivityLog.Add(log);
            _db.SaveChanges();
            base.OnActionExecuted(filterContext);
        }
    }

0 个答案:

没有答案