.NetCore 过滤器和拦截器 的区别

Asp.NET Core 中的过滤器(Filter)和拦截器(Interceptor)是两个不同的概念,但它们在某些方面有相似之处,也有明显的区别。

🔑过滤器(Filter)

过滤器是Asp.NET Core中用于在 Pipeline 中的特定阶段执行代码的一种机制。它可以用于处理请求和响应,例如:日志记录、身份验证、异常处理 等。

ASP.NET Core提供了多种内置的过滤器类型:

🔸 认证过滤器(Authentication Filter)

🔸 授权过滤器(Authorization Filter)

🔸 响应缓存过滤器(Response Cache Filter)

🔸 异常过滤器(Exception Filter)

🔸 结果过滤器(Result Filter)

🚫拦截器(Interceptor)

拦截器通常是在 AOP(面向切面编程)框架中使用的,如:Castle Windsor, Spring.NET等,它允许你在不修改原始代码的情况下,添加额外的行为。

在Asp.NET Core中,拦截器通常是通过 依赖注入 和 中间件 来模拟的。

两者区别

  1. 应用场景不同:过滤器 主要应用于 MVC 和 Web API 控制器中,而 拦截器 可以应用在任何对象或者数据。

  2. 实现方式不同:过滤器 通过 继承 特定的基类实现,而 拦截器通常通过 动态代理 实现。

  3. 控制粒度不同:过滤器 控制的 粒度更小,像是 Action,而 拦截器可以对 方法级别 的行为实施拦截。

  4. 性能差异:由于过滤器是在.NET Core的 Pipeline 中实现的,它的性能通常 优于拦截器。

示例代码

过滤器(Authentication Filter)

复制代码
public class MyCustomAuthFilter : Attribute, IAuthenticationFilter
{
    public Task AuthenticateAsync(AuthenticationContext context)
    {
        // 自定义认证逻辑
        return Task.CompletedTask;
    }
 
    public Task ChallengeAsync(AuthenticationChallengeContext context)
    {
        // 当需要challenge时执行
        return Task.CompletedTask;
    }
 
    public Task ForbidAsync(AuthenticationForbidContext context)
    {
        // 当需要forbid时执行
        return Task.CompletedTask;
    }
}
 
[MyCustomAuthFilter]
public IActionResult Index()
{
    return View();
}

拦截器(依赖注入和中间件模拟)

复制代码
// 定义一个拦截器接口
public interface IMyInterceptor
{
    Task InvokeAsync(InvocationContext context);
}
 
// 实现拦截器
public class MyInterceptor : IMyInterceptor
{
    public async Task InvokeAsync(InvocationContext context)
    {
        // 在调用方法之前执行额外的行为
        await Next(context); // 调用下一个拦截器或者原方法
        // 在调用方法之后执行额外的行为
    }
}
 
// 在中间件中使用
public class MyCustomMiddleware
{
    private readonly RequestDelegate _next;
 
    public MyCustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }
 
    public async Task InvokeAsync(HttpContext context, IMyInterceptor interceptor)
    {
        // 在这里调用拦截器
        await interceptor.InvokeAsync(/* 传递适当的参数 */);
        // 调用下一个中间件
        await _next(context);
    }
}
 
// 注册中间件
public void Configure(IApplicationBuilder app)
{
    app.UseMiddleware<MyCustomMiddleware>();
}

现在能区分二者的职责和关系了吧

相关推荐
夏霞2 天前
c# ASP.NET Core SignalR 客户端配置自动重连次数
c#·.netcore
BXS_null2 天前
windows、linux/ubuntu 系统运用.net core使用Selenium WebDriver实现自动化测试
linux·ubuntu·.netcore
切糕师学AI4 天前
.NET Core 如何使用 Quartz?
.netcore·quartz·作业调度
聪明努力的积极向上5 天前
【C#】System.Text.Encoding.Default 属性在framework和.netcore中的区别
开发语言·c#·.netcore
切糕师学AI6 天前
.NET Core Web + Vue 项目集成消息推送工具SignalR
vue.js·.netcore·signalr
万19996 天前
asp.net core webapi------3.AutoMapper的使用
c#·.netcore
dephixf8 天前
工业级部署指南:在西门子IOT2050(Debian 12)上搭建.NET 9.0环境与应用部署
物联网·.netcore·智能制造·边缘网关·西门子·iot 2050
睡前要喝豆奶粉8 天前
在.NET Core Web Api中使用JWT并配置UserContext获取用户信息
前端·.netcore
睡前要喝豆奶粉8 天前
在.NET Core Web Api中使用阿里云OSS
阿里云·c#·.netcore
周杰伦fans9 天前
.NET Core WebAPI 中 HTTP 请求方法详解:从新手到精通
网络协议·http·.netcore