首页 > 其他分享 >筛选器Filter

筛选器Filter

时间:2024-03-15 19:04:24浏览次数:25  
标签:Console Filter context 筛选 执行 public

参考:https://learn.microsoft.com/zh-cn/aspnet/core/mvc/controllers/filters?view=aspnetcore-6.0

1、什么是筛选器

通过使用 ASP.NET Core 中的筛选器,可在请求处理管道中的特定阶段之前或之后运行代码。

可以创建自定义筛选器,用于处理横切关注点。 横切关注点的示例包括错误处理、缓存、配置、授权和日志记录。 筛选器可以避免复制代码。 

(1)The request is processed through Other Middleware, Routing Middleware, Action Selection, and the Action Invocation Pipeline. The request processing continues back through Action Selection, Routing Middleware, and various Other Middleware before becoming a response sent to the client.(2)The request is processed through Authorization Filters, Resource Filters, Model Binding, Action Filters, Action Execution and Action Result Conversion, Exception Filters, Result Filters, and Result Execution. On the way out, the request is only processed by Result Filters and Resource Filters before becoming a response sent to the client.(3)

工作原理:筛选器在 ASP.NET Core 操作调用管道(有时称为筛选器管道)内运行。筛选器管道在 ASP.NET Core 选择了要执行的操作之后运行,如图(1)所示。

5种筛选器:每种筛选器类型都在筛选器管道中的不同阶段执行:授权筛选器AuthorizationFilter、资源筛选器Resource Filter、操作筛选器Action Filter、异常筛选器Exception Filter、结果筛选器Result Filter。图(2)展示了筛选器类型在筛选器管道中的交互方式。

实现:所有的Filter都实现接口IFilterMetadata,根据不同的业务类型,派生出了五个接口,分别对应五大类Filter,如图(3)所示。

筛选器通过不同的接口定义支持同步和异步实现。

同步筛选器在其管道阶段之前和之后运行。 例如,OnActionExecuting 在调用操作方法之前调用。 OnActionExecuted 在操作方法返回之后调用:

public class SampleActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        // Do something before the action executes.
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // Do something after the action executes.
    }
}

异步筛选器定义 OnActionExecutionAsync 方法:

public class SampleAsyncActionFilter : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(
        ActionExecutingContext context, ActionExecutionDelegate next)
    {
        // Do something before the action executes.
        await next();
        // Do something after the action executes.
    }
}

异常筛选器的同步实现OnException和异步实现OnExceptionAsync

 

2、异常筛选器——Exception Filter

在向响应正文写入任何内容之前,对未经处理的异常应用全局策略。

builder.Services.Configure<MvcOptions>(options =>
{
    options.Filters.Add<SampleExceptionFilter>();
});

自定义同步异常筛选器:

public class SampleExceptionFilter : IExceptionFilter
{
    private readonly IHostEnvironment _hostEnvironment;

    public SampleExceptionFilter(IHostEnvironment hostEnvironment) =>
        _hostEnvironment = hostEnvironment;

    public void OnException(ExceptionContext context)
    {
        if (!_hostEnvironment.IsDevelopment())
        {
            // Don't display exception details unless running in Development.
            return;
        }

        context.Result = new ContentResult//返回给客户端的值
        {
            StatusCode = 500,        
            Content = context.Exception.ToString()
        };
        context.ExceptionHandled = true;//为true时,其他ExceptionFilter不会再执行
    }
}

 以下代码测试异常筛选器:

[ApiController]
[Route("[controller]/[action]")]
public class ExceptionController : ControllerBase
{
    public void Index() =>System.IO.File.ReadAllText("D:\\A.txt");//读取不存在的文件
}

异常筛选器:

  • 非常适合捕获发生在操作中的异常。
  • 并不像错误处理中间件那么灵活。

建议使用中间件处理异常。 基于所调用的操作方法,仅当错误处理不同时,才使用异常筛选器。

 

3、操作筛选器——Action Filter

  • 实现 IActionFilter 或 IAsyncActionFilter 接口。
  • 在调用操作方法之前和之后立即运行。
  • 可以更改传递到操作中的参数。
  • 可以更改从操作返回的结果。
  • 不可在 Razor Pages 中使用。

全局筛选器服务注入到容器:

builder.Services.Configure<MvcOptions>(options =>
{
    options.Filters.Add<MyActionFilter1>();
    options.Filters.Add<MyActionFilter2>();
});

自定义异步操作筛选器:

/*ActionExecutingContext 提供以下属性:
ActionArguments - 用于读取操作方法的输入。
Controller - 用于处理控制器实例。
Result - 设置 Result 会使操作方法和后续操作筛选器的执行短路。*/
public class MyActionFilter1 : IAsyncActionFilter
{
	public async Task OnActionExecutionAsync(ActionExecutingContext context, 
		ActionExecutionDelegate next)
	{
		Console.WriteLine("MyActionFilter 1:开始执行");
		ActionExecutedContext r = await next();
		if (r.Exception != null)
		{
			Console.WriteLine("MyActionFilter 1:执行失败");
		}
		else
		{
			Console.WriteLine("MyActionFilter 1:执行成功");
		}
	}
}

public class MyActionFilter2 : IAsyncActionFilter
{
	public async Task OnActionExecutionAsync(ActionExecutingContext context, 
		ActionExecutionDelegate next)
	{
		Console.WriteLine("MyActionFilter 2:开始执行");
		ActionExecutedContext r = await next();
		if (r.Exception != null)
		{
			Console.WriteLine("MyActionFilter 2:执行失败");
		}
		else
		{
			Console.WriteLine("MyActionFilter 2:执行成功");
		}
	}
}

  以下代码测试操作筛选器:

[ApiController]
[Route("[controller]/[action]")]
[TypeFilter(typeof(MyActionFilter1))]//必须加
[TypeFilter(typeof(MyActionFilter2))]
public class ActionController : ControllerBase
{
    [HttpGet]
    public string GetData()
    {
        Console.WriteLine("执行GetData");
        return "yzk";
    }
}

////执行结果,控制台输出以下结果
//MyActionFilter1,开始执行
//MyActionFilter2,开始执行
//执行GetData控制器方法
//MyActionFilter2,执行成功
//MyActionFilter1,执行成功

 

标签:Console,Filter,context,筛选,执行,public
From: https://www.cnblogs.com/xixi-in-summer/p/18075919

相关文章

  • 什么是布隆过滤器(Bloom Filter)?以及布隆过滤器的详细说明。
    什么是布隆过滤器(BloomFilter)?以及布隆过滤器的详细说明。布隆过滤器(BloomFilter):​ 是一种空间效率高、时间复杂度低的数据结构,用于判断一个元素是否属于一个集合。它通过使用多个哈希函数和位数组来实现快速的成员存在性检测,但有一定的误判率。结构:位数组(BitArray):布隆过......
  • Excel的几点运用#高级筛选#IFNA#VLOOKUP
    高级筛选应用场景:今天导员发了一个excel表格,内容是整个学院的学生名单,而且是乱序的,没有专业班级的信息,现在老师要求我们去完善表格中的邮箱这一项。然而,在那么多的数据中去找到自己的名字还是比较费时费眼睛的,所以我想要从中筛选出我们班级的同学信息,以便班内同学找到自己的名字......
  • netfilter: iptable的使用
    netfilter相关网址官网:netfilter/iptablesprojecthomepageiptables基础知识详解_LarryHai6的博客-CSDN博客_iptables使用iptables进行端口转发-云+社区-腾讯云(tencent.com)原理图iptables1.原理叙述iptables具有Filter,NAT,Mangle,Raw四种内建表:1.Filter......
  • GEE C12 Filter,Map,Reduce
    目录一、Filter二、Map三、Reduce一、Filter1.1 FilterDate 1.用法ImageCollection.filterDate('2010-01-01','2010-01-01')//varimgCol=ee.ImageCollection('LANDSAT/LT05/C02/T1_L2');//HowmanyTier1Landsat5imageshaveeverbeenc......
  • 探索Flutter中的模糊毛玻璃滤镜效果:ImageFilter介绍使用和深入解析
    在Flutter中,模糊效果不仅可以增加应用的视觉吸引力,还可以用于多种场景,如背景模糊、图像处理等。通过BackdropFilter和ImageFilter.blur,Flutter使得添加和调整模糊效果变得异常简单。本文将深入探讨如何在Flutter中实现动态模糊效果,并通过TileMode参数调整模糊效果的边缘行为......
  • installEventFilter、eventFilter函数理解
    installEventFilter函数如下:voidQObject::installEventFilter(QObject*filterObj)Qt助手的解释如下:在对象上安装一个事件过滤器filterObj。如下:monitoredObj->installEventFilter(filterObj);其中monitoredObj、filterObj都是QObject的子类。上面代码意思是:在monitoredObj......
  • spring-security源码-FilterChainProxy
    FilterChainProxy内部存储了我们各个HttpSecurty生成的SecurityFilterChain。FilterChainProxy实现了ServletFilter接口。只真正的入口org.springframework.security.web.FilterChainProxy.doFilterpublicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,F......
  • spring-security源码-如何初始化SecurityFilterChain到Servlet
    1.SecurityFilterChain是由HttpSecurty根据各个config配置生成的FilterSecurityFilterChain是接口,默认实现是由DefaultSecurityFilterChainSecurityFilterChain只充当描述的作用,描述哪些url走这批filterpublicfinalclassDefaultSecurityFilterChainimplementsSecurityF......
  • 启用和配置EWF(Enhanced Write Filter)通过命令行或者注册表等方式启用和配置EWF功能
     启用和配置EWF(EnhancedWriteFilter)功能,可以通过以下方式进行设置:命令行方式:打开命令提示符(以管理员身份运行)。使用以下命令启用EWF功能:ewfmgrc:-enable 这里的c:表示要启用EWF功能的逻辑磁盘,可以根据实际情况更改。若要禁用EWF功能,可以使用以下命令:ewfmgrc:-dis......
  • 达梦不支持filter类型的执行路径导致慢SQL
     达梦不支持filter类型的执行路径导致慢SQL 最近有个政府项目的库往政务云上迁移到达梦库,源库的业务量不是很大,库本身也不大。迁移后抓取达梦的AWR,发现有一条SQL每次执行需要15s多,而在原来的Oracle里边执行0.1s。查看后发现是达梦不支持filter执行路径导致的。模拟如下:创......