【问题标题】:How to filter out datatypes from Swagger schema?如何从 Swagger 模式中过滤掉数据类型?
【发布时间】:2022-04-02 23:08:39
【问题描述】:

我使用的是 Swasbuckle 5.6。

我的控制器有一个从第三方库继承的方法,该方法在公司范围内使用。

    [ProducesResponseType(typeof(HealthCheckActionResult), (int)HttpStatusCode.OK)]
    public HealthCheckActionResult Get()
    {
        return new HealthCheckActionResult(healthCheckService, healthCheckOptions);
    }

只要将该方法添加到我的控制器,我就会看到 Swagger UI 如何使用大量 CLR 内部类型来膨胀其架构定义:

当用于快速 API 测试时,这个庞大的架构会导致 UI 经常冻结。

我尝试了https://stackoverflow.com/a/61313313/217823 的答案,但它不起作用,因为 SchemaRepository 键不包含那些不需要的数据类型的完整命名空间名称。

假设我无法控制 HealthCheckActionResult 类(它来自第三方库),什么是摆脱它给 Swagger 架构带来的所有臃肿的正确方法?

【问题讨论】:

  • 你解决过这个问题吗?
  • @Yeronimo 是的,我做到了。在下面添加了我的解决方案作为答案。

标签: asp.net-core swagger swashbuckle


【解决方案1】:

我最终得到了一个忽略所有系统类型的解决方案,除了那些名称与我自己的类型有冲突的类型:

    // filter to stop the Swagger schema from bloating
    // because of API results that return complex CLR types
    internal class SwaggerExcludeClrTypesFilter : ISchemaFilter
    {
        private readonly string[] blacklist;
        // keep types that have matching System type names with our model
        private readonly string[] whitelist = new[] { "Currency" };

        public SwaggerExcludeClrTypesFilter()
        {
            var mscorlib = typeof(string).Assembly;
            var types = mscorlib.GetTypes()
                                .Where(t => t.Namespace?.Contains("System") == true);
            blacklist = types.Select(t => t.Name)
                .Where(t => !whitelist.Contains(t)).ToArray();
        }

        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            if (schema.Properties != null)
            {
                foreach (var prop in schema.Properties)
                {
                    if (prop.Value.Reference != null
                        && blacklist.Contains(prop.Value.Reference.Id))
                    {
                        prop.Value.Reference = null;
                    }
                }
            }

            foreach (var key in blacklist)
            {
                context.SchemaRepository.Schemas.Remove(key);
            }
        }
    }

然后在 Startup 类的 ConfigureServices 方法中:

services.AddSwaggerGen(c =>
            {
                ...

                // remove some third-party types that slow Swagger UI down
                c.SchemaFilter<SwaggerExcludeClrTypesFilter>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-12
    • 2017-09-21
    • 1970-01-01
    • 2020-08-13
    • 2022-11-22
    • 2018-10-19
    • 1970-01-01
    • 2021-12-03
    相关资源
    最近更新 更多