How can we create a LOG filter for Logging purposes in C# ASP.NET WebAPI?

Action filters are used to add extra logic before or after action methods execution. The OnActionExecuting and OnActionExecuted methods are used to add our logic before and after an action method is executed.

Let us create create a LogAttribute that implemets ActionFilterAttribute which logs some information before and after action method execution.



using System;
using System.Diagnostics;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace DemoWebApplication.Controllers{
   public class LogAttribute : ActionFilterAttribute {
      public override void OnActionExecuting(HttpActionContext actionContext){
         Debug.WriteLine(string.Format("Action Method {0} executing at {1}",
            actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()),
            "Web API Logs");
      public override void OnActionExecuted(HttpActionExecutedContext
         Debug.WriteLine(string.Format("Action Method {0} executed at {1}",
         DateTime.Now.ToShortDateString()), "Web API Logs");

Controller Action


using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      public IHttpActionResult Get(){
         //Some logic
         return Ok();

Since we have used the Log attribute which has the OnActionExecuting and OnActionExecuted methods implements, the log information will be added to the debug console.

Updated on: 19-Aug-2020


Kickstart Your Career

Get certified by completing the course

Get Started