Aspect Oriented Programming in ASP.NET MVC

后端 未结 1 1171
Happy的楠姐
Happy的楠姐 2021-02-03 13:10

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

1条回答
  •  一生所求
    2021-02-03 13:58

    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.

    0 讨论(0)
提交回复
热议问题