首页 > 其他分享 >.Net Core ActionFilter

.Net Core ActionFilter

时间:2023-07-08 20:12:34浏览次数:17  
标签:ActionFilter Core Console ActionExecutedContext Action Net CustomAsyncActionFilt

目录


作用

  • 在请求AuthorizeFilter -> ResourceFilter -> ActionFilter, 可以记录Action的日志
  • ActionFilter 在控制器实例化之后执行
  • ResourceFilter 可以在全局, Controller, Action 都可以设置, 并且都会执行(一个ResourceFilter可以重复设置)

如果都设置执行顺序为:

  1. 全局
  2. Controller
  3. Action
  4. Action 方法
  5. Action
  6. Controller
  7. 全局

实现

IActionFilter

  1. 需要继承 Attribute 并 并实现 IActionFilter
  2. 实现接口方法

执行顺序为:

  1. OnActionExecuting
  2. Action
  3. OnActionExecuted

IAsyncActionFilter

  1. 需要继承 Attribute 并 并实现 IAsyncActionFilter
  2. 实现接口方法
  3. 该接口只提供一个 OnActionExecutionAsync方法,如果想执行ActionExecutedContext方法,需要执行方法中ActionExecutionDelegate委托并取返回值然后代码在执行为
    ActionExecutedContext方法

执行顺序为:

  1. OnActionExecuting
  2. Action
  3. OnActionExecuted

ActionFilterAttribute

  1. 需要继承 ActionFilterAttribute
  2. 重写 OnActionExecuting OnActionExecuted OnResultExecuting OnResultExecuted 方法

执行顺序为:

  1. OnActionExecuting
  2. Action
  3. OnActionExecuted
  4. OnResultExecuting
  5. OnResultExecuted

Aop Action执行

过滤器代码

using Microsoft.AspNetCore.Mvc.Filters;

namespace Cnpc.Com.Ioc.WebApp.Filter.ActionFilter
{
    public class CustomAsyncActionFilter : Attribute, IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            {
                Console.WriteLine("ActionExecutingContext.....");
            }
            ActionExecutedContext executed = await next();
            {
                Console.WriteLine("ActionExecutedContext.....");
            }
        }
    }
}

Action代码

using Cnpc.Com.Ioc.WebApp.Filter;
using Microsoft.AspNetCore.Mvc;

namespace Cnpc.Com.Ioc.WebApp.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TestFilterController : ControllerBase
    {
        //[TypeFilter(typeof(CustomAsyncActionFilter))]  如果想在ActionFilter支持Nlog 并使用构造注入就这样写
        [CustomAsyncActionFilter]
        [HttpGet]
        public async Task Action_AsyncActionFilter()
        {
            Console.WriteLine("Func...");
            await Task.CompletedTask;
        }
    }
}

使用日志

Action

//[ServiceFilter(typeof(CustomAsyncActionFilter))] 如果使用SerciceFilter 要先将CustomAsyncActionFilter 注册到ioc中
[TypeFilter(typeof(CustomAsyncActionFilter))] //如果想在ActionFilter支持Nlog 并使用构造注入就这样写
[HttpGet]
public async Task Action_AsyncActionFilter()
{
    Console.WriteLine("Func...");
    await Task.CompletedTask;
}
CustomAsyncActionFilter.cs
using Cnpc.Com.Ioc.IBll;
using Cnpc.Com.Ioc.IDal;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Cnpc.Com.Ioc.WebApp.Filter.ActionFilter
{
    public class CustomAsyncActionFilter : Attribute, IAsyncActionFilter
    {

        ILogger<CustomAsyncActionFilter> logger { get; set; }
        IStudent student { get; set; }
        IWrite write { get;set; }
        public CustomAsyncActionFilter(ILogger<CustomAsyncActionFilter> logger,IStudent student,IWrite write)
        {
            this.logger = logger;
            this.student = student;
            this.write = write;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            {
                Console.WriteLine("ActionExecutingContext.....");
                logger.LogInformation(context.HttpContext.Request.Path + "before..");
                this.student.DoHomeWork(write);
            }
            ActionExecutedContext executed = await next();
            {
                Console.WriteLine("ActionExecutedContext.....");
                logger.LogInformation(context.HttpContext.Request.Path + "after..");
            }
        }
    }
}

全局注册

Program.cs

//全局注册
builder.Services.AddControllersWithViews(options =>
{
    options.Filters.Add<CustomAsyncActionFilter>();
});

标签:ActionFilter,Core,Console,ActionExecutedContext,Action,Net,CustomAsyncActionFilt
From: https://www.cnblogs.com/qfccc/p/17537763.html

相关文章

  • Net 编译器平台--- Roslyn Scripting APIs
    引言上一篇中.Net编译器平台---Roslyn,介绍了Roslyn的各项功能,包括公开API,使用语法,使用语义,使用工作区等功能。那么回到上一篇中提到的问题,实现类似这样的功能(以下代码为伪代码):stringscriptText="inta=1;intb=2;returna+b;";varresult=Script.Run(scriptTex......
  • 03-kubeadm初始化Kubernetes集群
    集群部署架构规划:节点网络:192.168.1.0/24Service网络:10.96.0.0/12Pod网络:10.244.0.0/16  部署方法参考:https://github.com/kuberneteskop方式:AWS(AmazonWebServices)andGCE(GoogleCloudPlatform)arecurrentlyofficiallysupportedkubeadm方式:https://github.com......
  • .net core 6.0 mvc js对文件分片上传文件+控制器合并文件保存
    js,通过ajax将文件分片提交  遇到问题:.netcore6.0mvc上传文件位置主文件夹下的\bin\Debug\net6.0 文件访问不了问题在startup配置#region让upload文件夹可以外部访问stringsUploadPath="/upload";stringsFDir=ToolsBasic.UsPath(sUploadPath);if(!Direc......
  • ASP.NET Core SignalR 系列(二)- 中心(服务端)
    本章将和大家分享ASP.NETCoreSignalR中的中心(服务端)。本文大部分内容摘自微软官网:https://learn.microsoft.com/zh-cn/aspnet/core/signalr/hubs?view=aspnetcore-7.0废话不多说,我们直接来看一个Demo,Demo的目录结构如下所示:本Demo的Web项目为ASP.NETCoreWeb应用程序(目......
  • 一文彻底搞懂MySQL基础:B树和B+树的区别 转载 https://blog.csdn.net/a519640026/arti
    写在前面大家在面试的时候,肯定都会被问到MySql的知识,以下是面试场景:面试官:对于MySQL,你对他索引原理了解吗?我:了解面试官:MySQL的索引是用什么数据机构的?我:B+树面试官:为什么要用B+树,而不是B树?我:…面试官:用B+树作为MySql的索引结构,用什么好处?我:…B树和B+树是MySQL索引使用的数据结构......
  • Net 编译器平台 --- Roslyn
    引言最近做一个功能想要动态执行C#脚本,就是预先写好代码片段,在程序运行时去执行代码段,比如像这样(以下代码为伪代码):stringscriptText="inta=1;intb=2;returna+b;";varresult=Script.Run(scriptText);查阅了一些资料,发现.Net的开源编译器平台-Roslyn,可以支......
  • 在 kubernets pod 里使用 perf 直接调试 rust 程序
     我们想要了解我们程序在运行时候的真实情况,但是感觉rust性能方面的调试真的比go麻烦非常多。首先在rustcargo.toml中添加[profile.release]debug=true 直接在pod里面进行调试限制比较多,首先我们可能需要安装一些必要的东西比如perf本体在ubuntu的环境......
  • Docker.DotNet 库的使用(二)— 项目结构(选看)
    前言:本来想随便搭一个项目主要是介绍库的使用,搭着搭着变了样......
  • Hello-FPGA CoaXPress 2.0 FPGA HOST IP Core Demo User Manual
     目录Hello-FPGACoaXPress2.0HostFPGAIPCoreDemo41说明42设备连接53VIVADOFPGA工程64SDK工程9图1‑1VIVADO工程目录结构4图1‑2SDK工程目录结构4图2‑1ZCU102结构图5图2‑2ZCU102UART接口6图3‑1VIVADO工程6图3‑2CPU控制器7图......
  • 解决QNetworkConfigurationManager::onlineStateChanged不触发的具体操作步骤
    解决QNetworkConfigurationManager::onlineStateChanged不触发的问题作为一名经验丰富的开发者,我将向你解释如何解决"QNetworkConfigurationManager::onlineStateChanged不触发"的问题。首先,让我们了解一下整个流程,然后逐步进行代码实现。流程概述下面是解决问题的流程概述:......