zoukankan      html  css  js  c++  java
  • ASP.NET Core 移除已注册的过滤器

    背景

    ABP vNext 默认对异常响应进行了处理,现在某个项目需要自定义异常响应结果。

    问题

    在 ABP vNext 的 MVC 模块当中,可以看到是通过 AddService(typeof(AbpExceptionFilter)) 添加的过滤器。最初我的想法是在 ConfigureService() 生命周期方法内,使用 Configure<MvcOptions> 移除已经注册的过滤器。
    找到对应的 Remove() 方法,发现需要提供一个 IFilterMetadata 对象,顿时懵逼。

    解决

    通过查阅 AddService() 方法的源码,看到底层是通过 ServiceFilterAttribute 将一个过滤器类型包裹起来。最后将其强转为一个 IFilterMetadata 扔进集合,有强转这一步我们翻阅源码可以看到 ServiceFilterAttribute 应该是实现了这个接口的。

    public IFilterMetadata AddService(Type filterType, int order)
    {
        if (filterType == (Type) null)
        throw new ArgumentNullException(nameof (filterType));
        ServiceFilterAttribute serviceFilterAttribute = typeof (IFilterMetadata).IsAssignableFrom(filterType) ? new ServiceFilterAttribute(filterType)
        {
        Order = order
        } : throw new ArgumentException(Resources.FormatTypeMustDeriveFromType((object) filterType.FullName, (object) typeof (IFilterMetadata).FullName), nameof (filterType));
        this.Add((IFilterMetadata) serviceFilterAttribute);
        return (IFilterMetadata) serviceFilterAttribute;
    }
    

    那么我们只需要在 Remove() 方法当中传递一个 ServiceFilterAttribute 特性包装过滤器即可。

    context.Services.Configure<MvcOptions>(op =>
    {
        var abpExceptionFilter = new ServiceFilterAttribute(typeof(AbpExceptionFilter));
        op.Filters.Remove(abpExceptionFilter);
    });
    

    如果需要添加自己的过滤器,只需要调用 AddService(typeof(YourFilter)) 注册。

  • 相关阅读:
    java 复习001
    Some_sort_algorithms
    Install_pygments
    Install_ruby
    Ubuntu_wifi&pppoe
    Some_problem_with_octopress
    复习C语言
    VSim [a Racing-simulator by Vell001]
    Hello, Github Blog
    我的新计划 《2Dof Racing Simulator》2014/3/9 20:30:00
  • 原文地址:https://www.cnblogs.com/myzony/p/14021517.html
Copyright © 2011-2022 走看看