ScubaSteve
ScubaSteve

Reputation: 8270

How to specify Swagger specification extensions via code?

I am trying to add custom properties into the info section of the swagger.json that gets generated. I found many articles that talk about how to add the properties in the json by prefixing them with "x-". (ex: https://swagger.io/specification/#specification-extensions)

But, I cannot find anything that shows how to do this via C# code. (Currently using .NET 5)

We currently set the standard properties like so:

options.SwaggerDoc(Swagger.Version, new OpenApiInfo
{
  Title = "Service Api",
  Version = Swagger.Version,
  Description = "This describes the routes associated with the Service Api."
});

Just to test this, I tried extending OpenApiInfo like so:

public class CustomInfo : OpenApiInfo
{
  [JsonPropertyName("x-test")]
  public String Test;
}

then altering the SwaggerDoc like so:

options.SwaggerDoc(Swagger.Version, new CustomInfo
{
  Title = "Service Api",
  Version = Swagger.Version,
  Description = "This describes the routes associated with the Service Api.",
  Test = "New Value"
});

This did not work. How can I add a custom property (specification extension) to the api info?

Upvotes: 2

Views: 3420

Answers (1)

ScubaSteve
ScubaSteve

Reputation: 8270

I found that you can easily add the custom properties (specification extensions) to the OpenApiInfo's Extension property. You do not need to create your own classes that implement IOpenApiExtension for the value of the Dictionary. The class that came with the Swagger nuget package that I used was OpenApiString

options.SwaggerDoc(Swagger.Version, new OpenApiInfo
{
  Title = "Service Api",
  Version = Swagger.Version,
  Description = "This describes the routes associated with the Service Api.",
  Extensions = new Dictionary<string, IOpenApiExtension>
  {
    { "x-company", new OpenApiString("Company Name") },
    { "x-contact", new OpenApiString("[email protected]") }
  }
});

There are many other ready to use classes like OpenApiBoolean, OpenApiDateTime, or if you need an object, OpenApiObject. There are many others as well.

Upvotes: 4

Related Questions