ASP.NET MVC 中的面向方面编程 [英] Aspect Oriented Programming in ASP.NET MVC

查看:30
本文介绍了ASP.NET MVC 中的面向方面编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在 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.

我还需要访问 Http 请求,以便获取客户端信息.

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

有没有集成的方法来做到这一点?ASP.NET MVC 可以像 Java 中的 AspectJ 一样与方面文件一起使用吗?

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.)

非常感谢!

推荐答案

您可以使用属性以面向方面的方式实现功能.你想用你的功能包围的动作方法然后只需要用你的属性装饰:

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();
}

您可以使用属性、整个控制器装饰单个操作方法,甚至可以通过 ASP.NET MVC 的 GlobalFilterCollection 全局应用该属性.

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
    }

    // ...
}

ActionFilterAttribute 类允许您覆盖几个方法,以便您可以连接到 ASP.NET MVC 的操作执行管道:

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

您可以通过传递给上述方法的参数(如ActionExecutedContext)访问请求变量.

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

这篇关于ASP.NET MVC 中的面向方面编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆