mvc filter 的用法

1、建个类在model里面名字随便

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RHRSP.Web.Controllers.Common;

namespace RHRSP.Web.Models
{
    public class DemoActionAttributeFilter : ActionFilterAttribute
    {
        public string Message { get; set; }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        { //在Action执行之后执行 输出到输出流中文字:After Action Excute xxx
           // filterContext.HttpContext.Response.Write(@"<br />After Action Excute" + "\t " + Message);
          //  base.OnActionExecuted(filterContext);
           
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        { //在Action执行前执行
            //filterContext.HttpContext.Response.Write(@"<br />Before Action Excute" + "\t " + Message);
            //base.OnActionExecuting(filterContext);
                 
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        { //在Result执行之后 
           // filterContext.HttpContext.Response.Write(@"<br />After ViewResult Excute" + "\t " + Message);
           // base.OnResultExecuted(filterContext);              
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        { //在Result执行之前
           // filterContext.HttpContext.Response.Write(@"<br />Before ViewResult Excute" + "\t " + Message);
           // base.OnResultExecuting(filterContext);
        }

    }
}

2、要在哪个controller触发。就把该filter特性写在上面,如:

 [DemoActionAttributeFilter(Message = "action")]
    public class IndexController : Controller
    {

3、这样就可以用了,调用action前,后,调用result前,后。顺序把注释去掉就可以实验了

你可能感兴趣的:(filter)