在.net core web api中添加自定义属性到OpenAPI规范文件和swagger

Posted

技术标签:

【中文标题】在.net core web api中添加自定义属性到OpenAPI规范文件和swagger【英文标题】:Add custom attribute to OpenAPI specification file and swagger in .net core web api 【发布时间】:2021-11-27 10:18:02 【问题描述】:

我有一个 .Net Core 5 Web API 项目 (C#),我在其中添加并配置了 Swagger.Net。一切正常,但现在客户要求我在 OAS 文件中添加“自定义属性”以指定 API 尚未准备好投入生产:

x-acme-production-ready=false

到今天我一直提供Swagger自动生成的json文件。

如何生成具有如下结构的 OAS 文件:

openapi: "3.0.0"

# REQUIRED - Formal commitments from the API focal point
x-acme-api-commitments:
  api-100: We commit to providing a proper valid OpenAPI (swagger) specification file for each API change.....

# REQUIRED - List of versions changes
x-acme-api-changelog: 
  - version: 1.0.0
    changes: Add GET /example
  - version: 1.1.0
    changes: Add POST /example

info: 
  # REQUIRED - Functional descriptive name of the API. 
  title: ACME - Basic template API 

上面的文件看起来像是 JSON 的文本表示,所以可能应该足以将自定义字段 x-acme-production-ready 添加到 JSON,但我该如何添加它以编程方式?

********* 更新 ***********

看上面的规范,这个自定义字段应该是在JSON swagger中与标签“info”同级添加的:

   openapi: "3.0.1",
   x-acme-production-ready: "true",
   info: 
       title: "my-app-title",
       version: "v1.0"
   ,
   servers: [
       
           url: "https://localhost:44370"
       
   ],
   paths: ...

我已将类 CustomModelDocumentFilter 添加到我的项目中,但我不明白如何以及在何处调用它,以及如何使用它在该位置添加该字段。

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections.Generic;

namespace MyApp.Swagger

    public class CustomModelDocumentFilter : IDocumentFilter
    
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        
            swaggerDoc....
        
    

在我的创业中,我有:

services.AddSwaggerGen(c =>
       
          c.DocumentFilter<Swagger.CustomModelDocumentFilter>();
          c.SwaggerDoc("v1.0", new OpenApiInfo  Title = "my app title", Version = "v1.0", Description = "my app description." );

          string xmlFile = $"Assembly.GetExecutingAssembly().GetName().Name.xml";
          string xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

       );

【问题讨论】:

“Swagger.Net”是指Swagger-Net 还是Swashbuckle.AspNetCore? @Helen 我正在使用 Swashbuckle.AspNetCore 【参考方案1】:

如果您使用 Swashbuckle.AspNetCore,您可以使用 document filter 自定义 OpenAPI 文档。

【讨论】:

谢谢你的回复,好像是这样的,但是我真的不明白应该怎么用,我得叫它...

以上是关于在.net core web api中添加自定义属性到OpenAPI规范文件和swagger的主要内容,如果未能解决你的问题,请参考以下文章

asp.net core 2.0 web api基于JWT自定义策略授权

Asp.Net Core Web API 5.0 和 Angular 中基于自定义角色的授权

.Net Core Web Api返回的json数据,自定义日期格式

Bootstrap5 和其他自定义 CSS 未在 .net core web api 中加载

ASP.NET Core Web API

ASP.NET Core API:添加自定义路由令牌解析器