繁体   English   中英

OpenAPI 自动生成的 C# 服务器引发 UriFormatException

[英]OpenAPI auto-generated C# server raising UriFormatException

我试图让最基本的 OpenAPI 服务器按预期工作。 它与自动生成的 python-flask 一起按预期工作,但不适用于在查询中引发异常的 aspnet。

需要哪些额外步骤才能让 aspnet 服务器正确响应查询?

YAML 如下:

openapi: 3.0.0
info:
  title: Test API
  version: 0.0.0  
servers:
  - url: http://localhost:{port}
    description: Local server
    variables:
      port:
        default: "8092"    
paths:
  /things:
    get:
      summary: Return a list of Things
      responses:
        '200':
          description: A JSON array of Things
          content:
            application/json:
              schema: 
                type: array
                items: 
                  $ref: "#/components/schemas/Thing" 
components:
  schemas:
    Thing:
      properties:
        id:
          type: integer
        name:
          type: string

为了让服务器运行,自动生成的 launchSettings.json 必须修改为:

...
    "web": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
...

到:

...
    "web": {
      "commandName": "Project",
      "launchBrowser": false,
      "launchUrl": "swagger",
      "applicationUrl": "http://localhost:8092",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
...

控制台提示服务器运行正常

info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using 'C:\Users\jonathan.noble\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
Hosting environment: Development
Content root path: D:\aspnetcore-server-generated\src\IO.Swagger
Now listening on: http://localhost:8092
Application started. Press Ctrl+C to shut down.

但是,当通过http://localhost:8092/things (这是 swagger 编辑器建议使用的)进行查询时,服务器会抛出异常

info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
      Request starting HTTP/1.1 GET http://localhost:8092/things
fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HM46UOD2UM1E", Request id "0HM46UOD2UM1E:00000001": An unhandled exception was thrown by the application.
System.UriFormatException: Invalid URI: The URI is empty.
   at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
   at System.Uri..ctor(String uriString)
   at IO.Swagger.Startup.<ConfigureServices>b__5_2(SwaggerGenOptions c) in D:\aspnetcore-server-generated\src\IO.Swagger\Startup.cs:line 73
   at Microsoft.Extensions.Options.ConfigureNamedOptions`1.Configure(String name, TOptions options)
...

通过查看自动生成的代码与aspnet-core 中的示例项目之间的差异,我发现了导致异常的一行代码。

在 Program.cs 中需要删除自动生成的代码

c.OperationFilter<GeneratePathParamsValidationFilter>();

我确定它的存在是有原因的,但它导致基本应用程序失败。

使用swagger-codegen-cli codegen swagger-codegen-cli版本 3.0.27,我遇到了同样的错误(我也只是生成最基本的 API 服务器)。 事实证明,生成器生成的代码尝试在Startup.ConfigureServices()使用空字符串实例化TermsOfService Uri对象:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v0", new OpenApiInfo
    {
        Version = "v0",
        Title = "Test API Spec",
        Description = "Test API Spec (ASP.NET Core 3.1)",
        Contact = new OpenApiContact()
        {
            Name = "Swagger Codegen Contributors",
            Url = new Uri("https://github.com/swagger-api/swagger-codegen"),
            Email = ""
        },
        TermsOfService = new Uri("")    // ********** right here **********
    });
    c.CustomSchemaIds(type => type.FullName);
    string xmlPath = Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml");
    c.IncludeXmlComments(xmlPath);

    // Include DataAnnotation attributes on Controller Action parameters as Swagger validation rules (e.g required, pattern, ..)
    // Use [ValidateModelState] on Actions to actually validate it in C# as well!
    //c.OperationFilter<GeneratePathParamsValidationFilter>();
});

我刚刚完全删除了服务TermsOfService字段,因此不再抛出错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM