How to add a Schema Filter to just one Swashbuckle api document version

陌路散爱 提交于 2021-02-10 18:35:36

问题


I have an issue, I use Swashbuckle 4 and it doesn't support polymorph, I found two filters that do that. One DocumentFilter and one SchemaFilter.

They work like charme.

But now I have an issue, I add a second version to my api. But I have a polymorph model which is just supported by version 2.

But I found no way to add these filters just to one api version, because they are added at Startup to the SwaggerGenOptions.

I'm little bit shocked that Swashbuckle does not seem to support Filters per version, because versions are exactly to separate two code worlds in one project.

Any ideas?


回答1:


The reason we need an example is because there are different ways of approaching versioning. I'm not sure how you are doing it, but usually a Model is versioned with a new class with the same name, but in a different Namespace, in which case there is no issue. Register all your Filters. They should know how to tell if the object being processed is the one they know how to handle. I'm not familiar with IDocumentFilter, but for ISchemaFilter:

    public class MyV1SchemaFilter : ISchemaFilter
    {
        public void Apply(Schema schema, SchemaFilterContext context)
        {
            if (context.SystemType != MyProject.Models.v1.MyModel) return;
            /// configure v1 schema
        }
    }

    public class MyV2SchemaFilter : ISchemaFilter
    {
        public void Apply(Schema schema, SchemaFilterContext context)
        {
            if (context.SystemType != MyProject.Models.v2.MyModel) return;
            /// configure v2 schema
        }
    }

You could also put it all in one Filter:

    public class MySchemaFilter : ISchemaFilter
    {
        public void Apply(Schema schema, SchemaFilterContext context)
        {
            if (context.SystemType == MyProject.Models.v1.MyModel)
            {
                /// configure v1 schema
            }
            else if (context.SystemType == MyProject.Models.v2.MyModel)
            {
                /// configure v2 schema
            }
        }
    }

If you are doing it in a way where both versions are somehow represented by the same Class, then maybe you need to separate them.

DocumentFilterContext seems like it has enough data in there for it to know which version it was passed, as well.



来源:https://stackoverflow.com/questions/59093955/how-to-add-a-schema-filter-to-just-one-swashbuckle-api-document-version

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!