Skip to content

过滤器与中间件相似,可在请求处理管道中的特定阶段之前或之后运行代码。

它分为全局过滤器,控制器级别过滤器,动作级别过滤器

工作原理

交互方式

有同步和异步两种实现: IActionFilter 和 IAsyncActionFilter,只能二选一,如果都实现,则系统调用异步版本。

自定义管道过滤器

csharp
public class TestFilter:IAsyncActionFilter
{
    IServiceProvider serviceProvider;
    public TestFilter(IServiceProvider serviceProvider)
    {
        this.serviceProvider=serciceProvider;
        //orderDomainService = serviceProvider.GetService(typeof(IOrderDomainService)) as IOrderDomainService;
    }
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        await next();
    }
}

定义属性标记

csharp
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class TestAttribute :Attribute, IFilterFactory
{
     public bool IsReusable => false;
     public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
	{
		var filter = new TestFilter(serviceProvider);
		return filter;
	}
}

详情可查阅微软官方文档

自定义方法拦截器

引用RsCode.AspNetCore.dll

csharp
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class IntegralPayAttribute : AbstractInterceptorAttribute
{
    //属性注入
	[FromServiceContext]
	public IHttpContextAccessor HttpContextAccessor { get; set; }
    
    public override  async Task Invoke(AspectContext context, AspectDelegate next)
    {
        await next(context);
    }
}