这个模式下的 aop 局限于 mvc 框架,因为它要继承 FilterAttribute, IActionFilter 。它两都在 system.web.mvc 命名空间下,所以仅支持在 Controller 中使用
首页定义一个特性类,并继承 FilterAttribute, IActionFilter
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} 执行前", 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} 执行后", url)); } }} 然后就可以在 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 执行..."); return View(); } public ActionResult About() { this.Response.Write("About 执行..."); return View(); } }}
运行效果1:\home\index
运行效果2:\home\about