Reputation: 2875
Using ASP.NET MVC 4 RTW, how do I log MVC controller actions and parameters to a database? I'd like to audit user actions but don't really want to duplicate a bunch of code inside every controller or, even worse, inside every action. Is there something i can implement globally? I understand the EF / database side of things so this is really about MVC.
Upvotes: 1
Views: 1170
Reputation: 12194
You should look at Custom Action Filters. Good MSDN article here http://msdn.microsoft.com/en-us/library/dd381609(v=vs.100).aspx
The filterContext.ActionDescriptor.ActionName would give you the name of the action to log, also the filterContext.ActionDescriptor.ControllerDescriptor.ControllerName will probably help and the parameters are held in filterContext.ActionParameters
These filters can be applied globally for all actions in the config Global.asax or in the App_Start folder under FilterConfig via.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new LoggingFilterAttribute());
}
Example Code for Attribute
public class LoggingFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Trace.Write("(Logging Filter)Action Executing: " +
filterContext.ActionDescriptor.ActionName);
base.OnActionExecuting(filterContext);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Exception != null)
filterContext.HttpContext.Trace.Write("(Logging Filter)Exception thrown");
base.OnActionExecuted(filterContext);
}
}
Upvotes: 2