Custom action filter attributes in request logging

MVC .NET provides abstract class ActionFilterAttribute with virtual methods:

  • OnActionExecuting Called before the action is called. It gives you the opportunity to look at information within the HttpContext and make decisions about whether the process should continue to be processed.
  • OnActionExecuted Enables you look at the results of an action and determine whether something needs to happen at that point.
  • OnResultExecuting Called before the action result from the action is processed.
  • OnResultExecuted Called after the action result is processed but before the output is loaded into the response stream.
    This class provides a great way to create class acting like an attribute on an action (or whole controller), in which we can put some business logic before and after current action is hit. Let’s take a real-life scenario, let say, we want to log some user information making the request (IP address) for security reasons. We want to create log entry and write it to some output (file, database).
public class LogRequestAttribute : ActionFilterAttribute, IActionFilter
  {
      void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
      {
         //Do some logic: Get some parameters and create log entry
         var ipLog = new LogEntry()
         {
            Message = string.Format(
            CultureInfo.InvariantCulture,
            "Action {0} Controller {1} Ip Address{2}",
            filterContext.Controller.ValueProvider.GetValue("action").RawValue,
            filterContext.Controller.ValueProvider.GetValue("controller").RawValue,
            GetUserIP(filterContext.Controller.ControllerContext.HttpContext.Request)
            ),
            LogType = LogType.Info,
            TimeStamp = filterContext.HttpContext.Timestamp
          };

          //Asynchronous write to file
          ThreadPool.QueueUserWorkItem(delegate
          {
              FileLogger.Write(ipLog);
          });

          base.OnActionExecuting(filterContext);
        }
}

After creating out custom action filter, we are ready to apply it. I decided to choose Login post action, because I would like to preview all login attempts (valid and invalid).

[LogRequest]
public ActionResult Login(LoginModel model, string returnUrl)
{
   //Do Stuff
   return View(model);
}

Summary
MVC .NET action filters give us the opportunity to manipulate with some business logic around actions or controllers elegant way. Above example is very simple, but we are allowed to put some more complex logic.

Source code is available here

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *