当前位置: 首页 > 知识库问答 >
问题:

.NET 5-swagger.json

鲁靖
2023-03-14
            //Register Swagger Options as Dependency Injection
        services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();
        
        services.AddSwaggerGen(options =>
        {
            // add a custom operation filter which sets default values
            //options.OperationFilter<SwaggerDefaultValues>();

            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            options.IncludeXmlComments(xmlPath);

        });

在启动-配置中

app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.InjectStylesheet("../css/customize-swagger-ui.css");
            c.InjectJavascript("../js/customize-swagger-ui.js");
            // build a swagger endpoint for each discovered API version
            foreach (var description in provider.ApiVersionDescriptions)
            {
                c.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());

            }

        });

我的问题是,我想在api-request后面添加方法的名称。另外,像NSWAG这样的客户端代码生成工具创建了许多不同的方法,它们被称为APIRoute1、APIRoute2、APIRoute3、...

下面是swagger生成的文件的JSON片段:

"paths": {
"/api/v1/Order": {
  "post": {
    "tags": [
      "Order"
    ],
    "summary": "Creates a new Order if no order currently exists",
    "requestBody": {
      "description": "",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/CreateOrderModel"
          }
        },
        "text/json": {
          "schema": {
            "$ref": "#/components/schemas/CreateOrderModel"
          }
        },
        "application/*+json": {
          "schema": {
            "$ref": "#/components/schemas/CreateOrderModel"
          }
        }
      }
    },
    "responses": {
      "200": {
        "description": "Success"
      }
    }
  }
},
"/api/v1/Order/{orderNumber}": {
  "get": {
    "tags": [
      "Order"
    ],
    "summary": "Reads a given Order if exists",
    "parameters": [
      {
        "name": "orderNumber",
        "in": "path",
        "description": "Order Number",
        "required": true,
        "schema": {
          "type": "integer",
          "format": "int32"
        }
      }
    ],
    "responses": {
      "200": {
        "description": "Success",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/OrderDTO"
            }
          }
        }
      },
      "400": {
        "description": "Bad Request",
        "content": {
          "application/json": {
            "schema": {
              "type": "string"
            }
          }
        }
      },
      "404": {
        "description": "Not Found",
        "content": {
          "application/json": {
            "schema": {
              "type": "string"
            }
          }
        }
      }
    }
  }
}
    /// <summary>
/// Configures the Swagger Options like Titel, Contact Informations etc
/// </summary>
public class ConfigureSwaggerOptions : IConfigureOptions<SwaggerGenOptions>
{
    readonly IApiVersionDescriptionProvider provider;

    /// <summary>
    /// Constructor which adds ApiVersionDescription by Dependency Injection
    /// </summary>
    /// <param name="provider">API Version Description Provider</param>
    public ConfigureSwaggerOptions(IApiVersionDescriptionProvider provider) => this.provider = provider;

    /// <summary>
    /// Adds a seperate Swagger Document for each API Version
    /// </summary>
    /// <param name="options">Swagger Generic Options</param>
    public void Configure(SwaggerGenOptions options)
    {
        foreach (var description in provider.ApiVersionDescriptions)
        {
            options.SwaggerDoc(description.GroupName, CreateInfoForApiVersion(description.ApiVersion.ToString(), description.IsDeprecated));
        }
    }

    /// <summary>
    /// Creates Header Informations for API
    /// </summary>
    /// <param name="description">ApiVersionDescription</param>
    /// <returns>Api Info</returns>
    static OpenApiInfo CreateInfoForApiVersion(string version, bool isDeprecated)
    {
        var info = new OpenApiInfo()
        {
            Title = "Rüstkontrolle API",
            Version = version,
            Description = "Service Dokumentation für das AddOn Rüstkontrolle im SICK Werkerportal",
            Contact = new OpenApiContact() { Name = "Lukas Adler", Email = "lukas.adler@sick.de" },
            License = new OpenApiLicense() { Name = "",}
        };

        if (isDeprecated)
        {
            info.Description += "API version is deprecated.";
        }
        return info;
    }
}
    /// <summary>
/// Swagger Operation Filter
/// </summary>
public class SwaggerDefaultValues : IOperationFilter
{
    /// <summary>
    /// Applies Operations and OperationsFilterContext on API Descriptions
    /// </summary>
    /// <param name="operation">Operation</param>
    /// <param name="context">OperationFilterContext</param>
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {

        var apiDescription = context.ApiDescription;

        if (operation.Parameters == null)
        {
            return;
        }

        foreach (var parameter in operation.Parameters)
        {
            var description = apiDescription.ParameterDescriptions.First(p => p.Name == parameter.Name);

            if (parameter.Description == null)
            {
                parameter.Description = description.ModelMetadata?.Description;
            }

            parameter.Required |= description.IsRequired;
        }
    }
}

NSWAG Konfiguration

    {
  "runtime": "NetCore21",
  "defaultVariables": null,
  "documentGenerator": {
    "fromDocument": "HERE IS NORMALLY MY API DESCRIPTION",
      "url": "https://localhost:44314/swagger/v1/swagger.json",
      "output": null,
      "newLineBehavior": "Auto"
    }
  },
  "codeGenerators": {
    "openApiToCSharpClient": {
      "clientBaseClass": null,
      "configurationClass": null,
      "generateClientClasses": true,
      "generateClientInterfaces": false,
      "clientBaseInterface": null,
      "injectHttpClient": true,
      "disposeHttpClient": true,
      "protectedMethods": [],
      "generateExceptionClasses": true,
      "exceptionClass": "ApiException",
      "wrapDtoExceptions": true,
      "useHttpClientCreationMethod": false,
      "httpClientType": "System.Net.Http.HttpClient",
      "useHttpRequestMessageCreationMethod": false,
      "useBaseUrl": true,
      "generateBaseUrlProperty": true,
      "generateSyncMethods": false,
      "generatePrepareRequestAndProcessResponseAsAsyncMethods": false,
      "exposeJsonSerializerSettings": false,
      "clientClassAccessModifier": "public",
      "typeAccessModifier": "public",
      "generateContractsOutput": false,
      "contractsNamespace": null,
      "contractsOutputFilePath": null,
      "parameterDateTimeFormat": "s",
      "parameterDateFormat": "yyyy-MM-dd",
      "generateUpdateJsonSerializerSettingsMethod": true,
      "useRequestAndResponseSerializationSettings": false,
      "serializeTypeInformation": false,
      "queryNullValue": "",
      "className": "{controller}Client",
      "operationGenerationMode": "MultipleClientsFromOperationId",
      "additionalNamespaceUsages": [],
      "additionalContractNamespaceUsages": [],
      "generateOptionalParameters": false,
      "generateJsonMethods": false,
      "enforceFlagEnums": false,
      "parameterArrayType": "System.Collections.Generic.IEnumerable",
      "parameterDictionaryType": "System.Collections.Generic.IDictionary",
      "responseArrayType": "System.Collections.Generic.ICollection",
      "responseDictionaryType": "System.Collections.Generic.IDictionary",
      "wrapResponses": false,
      "wrapResponseMethods": [],
      "generateResponseClasses": true,
      "responseClass": "SwaggerResponse",
      "namespace": "MyNamespace",
      "requiredPropertiesMustBeDefined": true,
      "dateType": "System.DateTimeOffset",
      "jsonConverters": null,
      "anyType": "object",
      "dateTimeType": "System.DateTimeOffset",
      "timeType": "System.TimeSpan",
      "timeSpanType": "System.TimeSpan",
      "arrayType": "System.Collections.Generic.ICollection",
      "arrayInstanceType": "System.Collections.ObjectModel.Collection",
      "dictionaryType": "System.Collections.Generic.IDictionary",
      "dictionaryInstanceType": "System.Collections.Generic.Dictionary",
      "arrayBaseType": "System.Collections.ObjectModel.Collection",
      "dictionaryBaseType": "System.Collections.Generic.Dictionary",
      "classStyle": "Poco",
      "jsonLibrary": "NewtonsoftJson",
      "generateDefaultValues": true,
      "generateDataAnnotations": true,
      "excludedTypeNames": [],
      "excludedParameterNames": [],
      "handleReferences": false,
      "generateImmutableArrayProperties": false,
      "generateImmutableDictionaryProperties": false,
      "jsonSerializerSettingsTransformationMethod": null,
      "inlineNamedArrays": false,
      "inlineNamedDictionaries": false,
      "inlineNamedTuples": true,
      "inlineNamedAny": false,
      "generateDtoTypes": true,
      "generateOptionalPropertiesAsNullable": false,
      "generateNullableReferenceTypes": false,
      "templateDirectory": null,
      "typeNameGeneratorType": null,
      "propertyNameGeneratorType": null,
      "enumNameGeneratorType": null,
      "serviceHost": null,
      "serviceSchemes": null,
      "output": null,
      "newLineBehavior": "Auto"
    }
  }
}

共有1个答案

殷功
2023-03-14

您可以使用swaggenoptions.customOperationIDs来指定您自己的自定义操作ID。例如。我使用以下设置:

services.AddSwaggerGen(c =>
{
    c.CustomOperationIds(x => ${x.ActionDescriptor.RouteValues["controller"]}_{x.ActionDescriptor.RouteValues["action"]}");
});

这将创建类似于client_getdetail的操作ID,您可以配置NSWAG来创建类似于clientapi.getdetail()的客户端API。

PS您在项目中使用Swashbuckle,如果您使用NSwag,那么它应该在默认情况下设置它。

 类似资料:
  • 我正在构建一个Azure函数项目,所以我不能以.NET5为目标。相反,我的项目是一个 。然而,当我的项目被构建时,只要有一些信息被打印出来,我就会看到DotNet5被提到。示例: 警告/usr/share/dotnet/sdk/5.0.101/microsoft.common.currentversion.targets(2123,5):警告MSB3245:无法解析此引用。找不到程序集“Syste

  • 我正试图将一个。NET5项目部署到google app engine上,但当我想用。NET5运行时构建时,它似乎有一个问题。

  • 升级到. NET5 for Azure Function后,此签名会引发以下异常。 Bash我已经按照留档https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-grid-trigger?tabs=csharp执行了 系统。NotSupportedException:“不支持对没有无参数构造函数

  • 我正在探索在上运行函数应用程序。这是我到目前为止所做的。 下面是新的< code>Program类,它取代了< code>Startup类: 我还有一个非常简单的HTTP触发函数: 我已经修改了我的 ,以指示函数必须在隔离模式下运行: 我使用以下参数启动函数: 问题 当我启动应用程序时,我收到以下警告消息: 我相信我在处于隔离进程中。我错过了什么? 更新 以下是版本信息:

  • 我有以下两种型号: 我可以绑定分类详细模型。NET5 mvc文件列表。问题是,我得到只有一个文件时,它张贴到。NET5 API.在我看来,MultipartFormDataContent在循环遍历每个文件时无法绑定多个文件。 下面的代码向API发送post请求 API控制器功能如下:

  • 我试图传达身份验证/安全方案需要设置一个头,如下所示: 这是我根据swagger文档所做的:

  • 我已经创建了一个proto文件,其中包含我打算生成的REST Web服务的所有必要消息和rpc函数。使用proc-gen-swagger插件,我设法将该proto文件编译成一个swagger.json文件,一切似乎都很好,除了两件事,我似乎无法解决。 > swagger.json文件中的所有定义都以我的原始文件包的名称为前缀。有没有办法摆脱这个? 我的消息的所有字段都是“可选的”。它们没有被明确指

  • 我正在使用go-swagger生成API服务器。我注意到json是由swagger生成的。yml保存在restapi/embedded\u spec.go中。 公开JSON规范以便我的ReactJS客户端可以访问它的最佳方式是什么? 到目前为止,我不得不使用招摇发球招摇。yml—端口=50000,并将JavaScript客户端指向本地主机:50000/swagger。json。我正在寻找一种通过A