using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Weee.Filter { public class MvcLogAttribute : ActionFilterAttribute, IActionFilter { private string _ActionDisplayName; private string _ModuleDisplayName; public MvcLogAttribute(string ActionDisplayName = null,string ModuleDisplayName=null) { _ActionDisplayName = ActionDisplayName; _ModuleDisplayName = ModuleDisplayName; } public Weee.DAL.WeeeDataContext db { get; set; } public override void OnActionExecuted(ActionExecutedContext filterContext) { var user = ((Controller)filterContext.Controller).ModelState["Username"] == null ? filterContext.HttpContext.User == null ? "" : filterContext.HttpContext.User.Identity.Name : ((Controller)filterContext.Controller).ModelState["Username"].Value.AttemptedValue; String message = String.Format( "Method=[{0}] ,User=[{1}], Action=[{2}], Controller=[{3}], IPAddress=[{4}]" + "TimeStamp=[{5}]", "OnActionExecuted", user, _ActionDisplayName??filterContext.ActionDescriptor.ActionName, _ModuleDisplayName??filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.HttpContext.Request.UserHostAddress, DateTime.Now); System.Diagnostics.Debug.WriteLine(message); var log = new Weee.Models.ActionLog() { Name = user, Action = _ActionDisplayName??filterContext.ActionDescriptor.ActionName, Controller = _ModuleDisplayName??filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, IP = filterContext.HttpContext.Request.UserHostAddress, ActionTime = DateTime.Now, ExecuteResult = filterContext.Exception == null ? ((Controller)filterContext.Controller).ModelState.IsValid? "success":"fail" : "exception: " + filterContext.Exception.Message + "\nstacktrace: " + filterContext.Exception.StackTrace }; db.ActionLogs.Add(log); db.SaveChanges(); base.OnActionExecuted(filterContext); } } }