Skip to content

OpenApiDocument.SerializeAsV2 throws UriFormatException when OpenApiServer.Url contains only a path #440

@cgreenza

Description

@cgreenza

OpenApiDocument.SerializeAsV2 throws the following exception when OpenApiServer.Url is set to a path only e.g. doc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = "/api" } }

System.UriFormatException
  HResult=0x80131537
  Message=Invalid URI: The format of the URI could not be determined.
  Source=System.Private.Uri
  StackTrace:
   at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
   at System.Uri..ctor(String uriString)
   at Microsoft.OpenApi.Models.OpenApiDocument.WriteHostInfoV2(IOpenApiWriter writer, IList`1 servers)
   at Microsoft.OpenApi.Models.OpenApiDocument.SerializeAsV2(IOpenApiWriter writer)
   at OpenApiTest.Program.Main(String[] args)

OpenApiDocument.SerializeAsV3 works fine with server URLs that contain only a path.

The OpenAPI V2 Specification allows for independent setting of basePath and host, so setting only a path should be possible.

Setting the basePath is needed for cases where multiple APIs are hosted in different virtual directories on the same host. Not setting the host is useful because the server generating the swagger document does then not need to know the hostname that clients are using to access it.

Below the code to reproduce this exception:

static void Main(string[] args)
{
    var document = CreateDocument("/api"); // http://petstore.io/api works in all cases

    var w1 = new OpenApiJsonWriter(new StringWriter());
    document.SerializeAsV2(w1); // fails with exception

    var w2 = new OpenApiJsonWriter(new StringWriter());
    document.SerializeAsV3(w2); // success
}

static OpenApiDocument CreateDocument(string serverUrl)
{
    return new OpenApiDocument {
        Info = new OpenApiInfo {
            Version = "1.0.0",
            Title = "Swagger Petstore",
        },
        Servers = new List<OpenApiServer> {
            new OpenApiServer { Url = serverUrl }
        },
        Paths = new OpenApiPaths {
            ["/pets"] = new OpenApiPathItem {
                Operations = new Dictionary<OperationType, OpenApiOperation> {
                    [OperationType.Get] = new OpenApiOperation()
                }
            }
        }
    };
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    type:bugA broken experience

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions