自定义asp.net mvc Filter 过滤器

时间:2021-10-22 23:50:41

1新建一个mvc项目:如图

自定义asp.net mvc Filter 过滤器

2、主要创建下面一些类文件

自定义asp.net mvc Filter 过滤器

1、utility目录 放置自定义的过滤器

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing; namespace WebAppTest.utility
{
//自定义LogActionFilter继承ActionFilterAttribute
public class LogActionFilter : ActionFilterAttribute
{
/// <summary>
/// 重写ActionFilterAttribute中的方法
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Log("OnActionExecuting", filterContext.RouteData);
} public override void OnActionExecuted(ActionExecutedContext filterContext)
{
Log("OnActionExecuted", filterContext.RouteData);
} public override void OnResultExecuting(ResultExecutingContext filterContext)
{
Log("OnResultExecuting", filterContext.RouteData);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
Log("OnResultExecuted", filterContext.RouteData);
}
//日志输出
private void Log(string methodName, RouteData routeData)
{
var controllerName = routeData.Values["controller"];
var actionName = routeData.Values["action"];
var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
Debug.WriteLine(message, "Action Filter Log");
} }
}





using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Mvc; namespace WebAppTest.utility
{
public class CustomerFilterAttribute : System.Web.Mvc.ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//base.OnActionExecuting(filterContext);
filterContext.HttpContext.Response.Write("开始时间:" + DateTime.Now.ToString() + "<br/>");
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
//base.OnActionExecuted(filterContext);
var controllerName = filterContext.RouteData.Values["controller"].ToString();
var actionName = filterContext.RouteData.Values["action"].ToString();
filterContext.HttpContext.Response.Write("结束时间:" + DateTime.Now.ToString() + "<br/>");
filterContext.HttpContext.Response.Write("controller:" + controllerName + ",action:" + actionName);
}
}
}