AuditLogActionFilter Class File
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace SampleAudit
{
public class AuditLogActionFilter : ActionFilterAttribute
{
public string ActionType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Retrieve the information what we need to log
string routeInfo = GetRouteData(filterContext.RouteData);
string user = filterContext.HttpContext.User.Identity.Name;
Debug.WriteLine(String.Format("ActionExecuting - {0} ActionType: {1}; User:{2}"
, routeInfo, ActionType, user), "Audit Log");
base.OnActionExecuting(filterContext);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Retrieve the information what we need to log
string routeInfo = GetRouteData(filterContext.RouteData);
bool isActionSucceeded = filterContext.Exception == null;
string user = filterContext.HttpContext.User.Identity.Name;
Debug.WriteLine(String.Format("ActionExecuted - {0} ActionType: {1}; Executed successfully:{2}; User:{3}"
, routeInfo, ActionType, isActionSucceeded, user), "Audit Log");
base.OnActionExecuted(filterContext);
}
private string GetRouteData(RouteData routeData)
{
var controller = routeData.Values["controller"];
var action = routeData.Values["action"];
return String.Format("Controller:{0}; Action:{1};", controller, action);
}
}
}