Aspect Oriented Programming in ASP.NET MVC

I am currently developing an MVC application in ASP.NET, and I am trying to separate the problems so that I end up with a cleaner and more customizable code.

So, as a starting point, I was thinking about the logging aspect. My idea is to register (initially) a call and return of each method in each controller. I would have this logic in a separate class devoted to logging, so I do not use my code with logging operators everywhere.

I also need access to the Http request so that I can get client information.

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

Also, is it possible to later configure the log settings that satisfy certain conditions? (e.g. signature, return value, exception throw, etc.)

Thank you very much in advance!

+7
c # logging aop asp.net-mvc
source share
1 answer

You can use attributes to implement a function in terms of aspect. The methods of actions that you want to surround with your functionality, you only need to decorate with your attribute:

[CustomLogger] public ActionResult Index() { // Doing something here ... return View(); } 

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

Here you can declare your attribute:

 public class CustomLoggerAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); // Here goes your logic } // ... } 

The ActionFilterAttribute class allows you to override several methods so that you can connect to the ASP.NET MVC execution pipeline:

  • OnActionExecuting
  • OnActionExecuted
  • OnResultExecuting
  • OnResultExecuted

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

+10
source share

All Articles