How to Log All WebAPI Request Response at ASP.NET MVC

2014/5/311 min read
bookmark this
Responsive image

Example of Log WebAPI MVC3 Controller

Example code of logging every request/response/exception when access to ASP.NET MVC 3 controller.


public class LogFilterAttribute : ActionFilterAttribute
    {
        ILog _log;

        public LogFilterAttribute()
            : this(null)
        {
        }
		
        public LogFilterAttribute(ILog log)
        {
			// TODO: define default ILog Service
            //_log = log ?? SomekindOfDefaultLogService()
        }
		
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string controllerNamespace = string.Format("{0} {1}Controller.{2} {3}",
                filterContext.HttpContext.Request.HttpMethod,
                filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                filterContext.ActionDescriptor.ActionName, "Request");
            var requestObject = new
            {
                Request = new
                {
                    Parameters = JsonConvert.SerializeObject(filterContext.ActionParameters),
                    Url = filterContext.HttpContext.Request.RawUrl,
                    Headers = JsonConvert.SerializeObject(filterContext.HttpContext.Request.Headers)
                }
            };

            _log.Save(controllerNamespace, JsonConvert.SerializeObject(requestObject));

            base.OnActionExecuting(filterContext);
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            string controllerNamespace = string.Format("{0}Controller.{1} {2}", filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.ActionDescriptor.ActionName, "Response");

            var reponseObject = new
            {
                Response = new
                {
                    StatusCode = filterContext.HttpContext.Response.StatusCode,
                    StatusDescription = filterContext.HttpContext.Response.StatusDescription,
                    Exception = JsonConvert.SerializeObject(filterContext.Exception)
                }
            };

            if (filterContext.Exception != null)
            {
                controllerNamespace = controllerNamespace + " Exception";
            }

            _log.Save(controllerNamespace, JsonConvert.SerializeObject(reponseObject));

            base.OnActionExecuted(filterContext);
        }
    }