首页 > 代码库 > 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 过滤器