Asp.net-Core
外部包中的模型顯示在 swagger 文件中
我正在處理 swagger 文件,並添加了一個外部包“ NodaTime ”,並用作模型中我的屬性的類型
public LocalDateTime Date { get; set; },來自NodaTime包的模型顯示在文件中。請查看螢幕截圖中的模型,突出顯示來自NodaTime包。為什麼 Swagger 將其包含在文件中以及如何從文件中排除外部包。提前致謝。
我不能使用,
DefaultModelExpandDepth(0);因為這會隱藏我自己的模型,我將其用作模型中的一種類型。所以,我曾經檢查哪些類型來自外部包並排除它們,如下所示。添加過濾器
public class RemoveVerbsFilter : IDocumentFilter { public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) { swaggerDoc.Definitions.Remove("LocalDateTime"); swaggerDoc.Definitions.Remove("CalendarSystem"); swaggerDoc.Definitions.Remove("Era"); swaggerDoc.Definitions.Remove("LocalTime"); swaggerDoc.Definitions.Remove("LocalDate"); } }添加啟動類ConfigureServices方法
services.AddSwaggerGen(c => { c.DocumentFilter<RemoveVerbsFilter>(); });
我猜他們出現是因為你暴露了一個使用 NodaTime 類型的對象。Swashbuckle / Swagger 正在顯示整個對像圖……如果您的模型使用這些模型,則無法關閉第三方的類似功能。如果你在 github 上查看庫中的程式碼,你可以看到 Swashbuckle 對幾個基類庫原語進行了特殊處理。方法是CreatePrimitiveSchema(),LocalDateTime不在case語句中。因此,作為解決此問題的方法,您可以分叉 Swashbuckle 並添加 NodaTime 類型。這可能不值得。
但是,Swashbuckle 允許您關閉模型擴展。下面你可以看到我的 Swashbuckle 配置設置。設置 DefaultModelsExpandDepth(-1) 將隱藏它們。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, DataGraphContext db) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1"); c.DefaultModelExpandDepth(0); c.DefaultModelsExpandDepth(-1); }); app.UseAuthentication(); app.UseExceptionHandling(); app.UseCors("AllowSpecificOrigins"); app.UseHttpsRedirection(); app.UseMvc(); }
