Matias Cicero Matias Cicero - 1 year ago 115
ASP.NET (C#) Question

Aspect Oriented Programming in ASP.NET MVC

Im currently developing an MVC application in ASP.NET and I'm trying to separate concerns so that I end up with cleaner and more maintanable code.

So, as a starting point, I was thinking of a logging aspect.
My idea is to log (initially) the calling and returning of every method in every controller.
I would have this logic on a separate class, dedicated to logging, so I don't mess my code with logging statements everywhere.

I would also need to have access to the Http Request so I can obtain client information.

Is there an integrated way to do this? Can ASP.NET MVC be used with aspect files just like AspectJ in Java?

Also, can it later be configured to log methods that satisfies certain conditions? (like signature, returning value, exception throwing, etc.)

Thanks very much in advance!

Answer Source

You can use attributes to implement a feature in an aspect-oriented way. Action methods that you want to surround with your functionality then only need to be decorated with your attribute:

public ActionResult Index()
    // Doing something here ...
    return View();

You can either decorate a single action method with an attribute, an entire controller, or even apply the attribute globally through ASP.NET MVC's GlobalFilterCollection.

Here's how you'd declare your attribute:

public class CustomLoggerAttribute : ActionFilterAttribute
    public override void OnActionExecuted(ActionExecutedContext filterContext)

        // Here goes your logic

    // ...

The ActionFilterAttribute class allows you to override a couple of methods so you can hook into ASP.NET MVC's action execution pipeline:

  • OnActionExecuting
  • OnActionExecuted
  • OnResultExecuting
  • OnResultExecuted

You can access request variables through the parameters (like ActionExecutedContext) that are passed to the above methods.