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 poi
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:
[CustomLogger]
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)
{
base.OnActionExecuted(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.