asp.net mvc Controller 模式下的 aop

这个模式下的 aop 局限于 mvc 框架,因为它要继承 FilterAttribute, IActionFilter 。它两都在 system.web.mvc 命名空间下,所以仅支持在 Controller 中使用

首页定义一个特性类,并继承 FilterAttribute, IActionFilter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace aspmvc_demo.Attributes
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class CommonMethodHoldAttribute : FilterAttribute, IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string url = string.Format(@"\{0}\{1}", filterContext.RouteData.Values["controller"], filterContext.RouteData.Values["action"]);
            filterContext.HttpContext.Response.Write(string.Format("{0} 执行前<br>", url));
        }
 
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            string url = string.Format(@"\{0}\{1}", filterContext.RouteData.Values["controller"], filterContext.RouteData.Values["action"]);
            filterContext.HttpContext.Response.Write(string.Format("{0} 执行后<br>", url));
        }
    }
}<br><br>然后就可以在 Controller 的中使用了,可以标记为类特性,也可以标记为方法的特性。我在这里标记为类的特性,就可以在这个类的所以方法执行前和执行后进行处理了using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using aspmvc_demo.Attributes;
 
namespace aspmvc_demo.Controllers
{
    [HandleError]
    [CommonMethodHold]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Message"] = "欢迎使用 ASP.NET MVC!";
            this.Response.Write("Index 执行...<br>");
            return View();
        }
 
        public ActionResult About()
        {
            this.Response.Write("About 执行...<br>");
            return View();
        }
    }
}

运行效果1:\home\index

运行效果2:\home\about

  

posted @   pophis  阅读(538)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示