首页 > 代码库 > MVC4 AactionFilter 过滤器
MVC4 AactionFilter 过滤器
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcRazor.Models {
//加上这个特性标签后,三种过滤器同时起作用
[AttributeUsage(AttributeTargets.All,AllowMultiple=true)]
public class MyActionFilterAttribute:ActionFilterAttribute
{ public string Name { get; set; } //Action执行之前执行 public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); HttpContext.Current.Response.Write("<br/> OnActionExecuting:" + Name+"<br/>"); } //Action执行之后执行 public override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); HttpContext.Current.Response.Write("<br/> OnActionExecuted:" + Name + "<br/>"); } //视图结果执行之前执行 public override void OnResultExecuting(ResultExecutingContext filterContext) { base.OnResultExecuting(filterContext); HttpContext.Current.Response.Write("<br/> OnResultExecuting:" + Name + "<br/>"); } //视图结果执行之后执行 public override void OnResultExecuted(ResultExecutedContext filterContext) { base.OnResultExecuted(filterContext); HttpContext.Current.Response.Write("<br/> OnResultExecuted:" + Name + "<br/>"); } } }
using MvcRazor.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcRazor.Controllers {
//Controller过滤器的优先级比Action过滤器低,比全局过滤器高 [MyActionFilter(Name = "Filter Controller")] public class FilterController : Controller { // // GET: /Filter/ public ActionResult Index() { return View(); } [MyActionFilter(Name = "TestActionFilter Action")] public ActionResult TestActionFilter() { Response.Write("<br/>Action被执行了<p></p><br/>"); return Content("<br/>视图被渲染了<br/>"); } public ActionResult TestControllerFilter() { Response.Write("<br/>Action被执行了<p></p><br/>"); return Content("<br/>视图被渲染了<br/>"); } } }
using MvcRazor.Models; using System.Web; using System.Web.Mvc; namespace MvcRazor { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); //新增全局过滤器,优先级最低,但是可以作用到所有的Controller和Action filters.Add(new MyActionFilterAttribute() { Name = "Global" }); } } }
MVC4 AactionFilter 过滤器
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。