.NET MVC5专题(特性篇【行为过滤】Action)

.NET MVC5专题 专栏收录该内容
16 篇文章 0 订阅

行为特性

public class MyActionFilterAttribute : ActionFilterAttribute
{
    #region Identity
    private Stopwatch timerAction = new Stopwatch();
    private Stopwatch timerResult = new Stopwatch();
    private bool _IsShow = false;
    public MyActionFilterAttribute(bool isShow = true)
    {
        this._IsShow = isShow;
    }
    #endregion
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (this._IsShow)
        {
            timerAction.Start();
            filterContext.HttpContext.Response.Write($"<h1 style='color:#00f'>这里是OnActionExecuting :{DateTime.Now.ToString("yyyyMMdd - HHmmss.fff")}</h1><hr>");
        }
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (this._IsShow)
        {
            timerAction.Stop();
            string message = $"<h1 style='color:#00f'>这里是OnActionExecuted:{DateTime.Now.ToString("yyyyMMdd-HHmmss.fff")},耗时{timerAction.ElapsedMilliseconds}</h1><hr>";
            filterContext.HttpContext.Response.Write(message);
        }
    }

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        if (this._IsShow)
        {
            timerResult.Start();
            filterContext.HttpContext.Response.Write("<h1 style='color:#00f'>这里是OnResultExecuting</h1><hr>");
        }
    }
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        if (this._IsShow)
        {
            timerResult.Stop();
            string message = $"<h1 style='color:#00f'>这里是OnResultExecuted:{DateTime.Now.ToString("yyyyMMdd - HHmmss.fff")},耗时 { timerResult.ElapsedMilliseconds}</h1><hr>";
            filterContext.HttpContext.Response.Write(message);
        }
    }
}

控制器和方法使用直接在前面加上[MyActionFilter]全局使用如下

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new MyActionFilterAttribute());
    }
}
  • 1
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值