ASP.NET Core 5.0 Web API 如何移除Swagger中OData生成的多余Schema
移除ASP.NET Core 5.0 Web API中Swagger生成的OData非业务Schema
可以通过自定义Swagger的Schema过滤器过滤OData命名空间下的所有类型,避免非业务Schema生成,操作步骤如下:
1. 实现自定义Schema过滤器
创建ODataSchemaFilter类,继承ISchemaFilter接口,实现OData类型过滤逻辑:
using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System.Linq; public class ODataSchemaFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { // 定义需要过滤的OData相关命名空间前缀 var excludedNamespaces = new[] { "Microsoft.OData", "Microsoft.AspNetCore.OData", "System.Web.OData" }; // 类型命名空间属于过滤范围时,清空Schema配置并标记为隐藏 if (context.Type.Namespace != null && excludedNamespaces.Any(ns => context.Type.Namespace.StartsWith(ns))) { schema.Properties.Clear(); schema.Deprecated = true; schema.Extensions.Add("x-hidden", true); } } }
2. 注册过滤器到Swagger配置
在项目Startup.cs的ConfigureServices方法中,注册刚才实现的过滤器:
services.AddSwaggerGen(c => { // 保留你原有的Swagger配置,例如接口文档信息、鉴权配置等 c.SwaggerDoc("v1", new OpenApiInfo { Title = "你的业务API", Version = "v1" }); // 注册OData Schema过滤器 c.SchemaFilter<ODataSchemaFilter>(); // 可选配置:开启忽略过时类型,配合过滤器自动隐藏标记为Deprecated的Schema c.IgnoreObsoleteProperties = true; });
可选:隐藏OData相关接口路由
如果不需要在Swagger中显示OData自带的$metadata等非业务接口,可以额外实现IDocumentFilter过滤接口路径:
- 实现
ODataDocumentFilter类
using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System; using System.Linq; public class ODataDocumentFilter : IDocumentFilter { public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { // 匹配所有包含OData标识或$符号的路径 var odataPaths = swaggerDoc.Paths .Where(p => p.Key.Contains("odata", StringComparison.OrdinalIgnoreCase) || p.Key.Contains("$")) .ToList(); // 移除匹配到的非业务接口 foreach (var path in odataPaths) { swaggerDoc.Paths.Remove(path.Key); } } }
- 在Swagger配置中注册该过滤器
services.AddSwaggerGen(c => { // 原有配置省略 c.DocumentFilter<ODataDocumentFilter>(); });
注意事项
- 如果你的业务接口确实需要用到OData命名空间下的某个类型作为入参/出参,可以调整
excludedNamespaces数组的过滤规则,添加例外逻辑避免误过滤 - 配置完成后可对比前后Swagger的Schema列表,确认过滤的都是非业务OData对象即可
内容的提问来源于stack exchange,提问作者Salman Tahir
相关产品推荐
相关产品推荐

