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

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

问题描述

即时通讯目前正在开发ASP.NET MVC应用程序,我试图让我结束了更清洁,更maintanable code分离的关注。

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.

所以,作为一个起点,我在想一个记录方面。
我的想法是日志(最初)调用,并在每个控制器的每一个方法的返回。
我会在一个单独的类,专用于记录这个逻辑,所以我不惹我的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使用方面的文件,就像AspectJ的Java中使用吗?

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
    }

    // ...
}

的<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.actionfilterattribute%28v=vs.118%29.aspx\"><$c$c>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

  • 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天全站免登陆