Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions docs/OpenApi/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ Configure via `CoreOpenApiOptions` (extends `OpenApiOptions`):

- `Title`, `Description`, `Version`, `DocumentName`
- `Servers` (`IList<OpenApiServerDescriptor>`)

> **Docker / port mapping:** In Development the library appends the addresses from
> `ASPNETCORE_URLS`/`DOTNET_URLS` as "Local" servers, but only when the host is a
> concrete (non-wildcard) address. When the app binds to a wildcard address such as
> `http://+:8080` (common in containers), or when the host port differs from the
> container port (for example `-p 80:8080`), the binding cannot be turned into a
> callable URL automatically. In those cases add the server manually, for example:
>
> ```csharp
> options.Servers.Add(new OpenApiServerDescriptor
> {
> Url = "http://localhost:80",
> Description = "Local"
> });
> ```
- `Bearer` security scheme
- `IncludeXmlComments`, `XmlCommentFiles`, `IncludeControllerXmlComments`
- `SwaggerRoutePrefix` (default `swagger`)
Expand Down
6 changes: 6 additions & 0 deletions docs/OpenApi/ProblemResponses.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ builder.Services.AddCoreOpenApi(options =>
});
```

`SchemaId` names the component that every problem response references. Its default
is `CoreProblemDetails`, the problem type shipped by this library, so the generated
document resolves without extra configuration. Set it only when your API uses a
different error type, and make sure a schema with that exact name exists; otherwise
the document contains a dangling `$ref`.

`IncludeWhenMissing` defaults to `false`, so a status code is only added to
operations that already declare it. An existing `400` is replaced only when it
already looks like a problem response.
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,16 @@ public static IServiceCollection AddCoreOpenApi(
var existing = new HashSet<string>(options.Servers.Select(s => s.Url), StringComparer.OrdinalIgnoreCase);
foreach (var url in urls.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
if (existing.Add(url))
if (IsWildcardListenAddress(url) || !existing.Add(url))
{
options.Servers.Add(new OpenApiServerDescriptor
{
Url = url,
Description = "Local"
});
continue;
}

options.Servers.Add(new OpenApiServerDescriptor
{
Url = url,
Description = "Local"
});
}
}
}
Expand All @@ -88,6 +90,24 @@ public static IServiceCollection AddCoreOpenApi(
return services;
}

/// <summary>
/// Determines whether a listen address uses a wildcard host, such as <c>http://+:8080</c>,
/// which is a binding pattern rather than an address a client can call.
/// </summary>
/// <param name="url">The listen address.</param>
/// <returns><see langword="true"/> when the host is a wildcard; otherwise, <see langword="false"/>.</returns>
private static bool IsWildcardListenAddress(string url)
{
var schemeEnd = url.IndexOf("://", StringComparison.Ordinal);
var authority = schemeEnd < 0 ? url : url[(schemeEnd + 3)..];
var host = authority.Split('/', 2)[0];
host = host.StartsWith('[')
? host[..(host.IndexOf(']') + 1)]
: host.Split(':')[0];

return host is "+" or "*" or "0.0.0.0" or "[::]";
}

/// <summary>
/// Configures the Swagger generator with the CoreSystem conventions.
/// </summary>
Expand Down
8 changes: 4 additions & 4 deletions src/Core.OpenApi/Options/OpenApiProblemResponsesOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ public OpenApiProblemResponsesOptions()
/// </summary>
/// <value>
/// The schema component name used when a definition does not declare its own.
/// The default value is <c>ProblemDetails</c>.
/// The default value is <c>CoreProblemDetails</c>, the problem type shipped by this library.
/// </value>
public string SchemaId { get; set; } = "ProblemDetails";
public string SchemaId { get; set; } = "CoreProblemDetails";

/// <summary>
/// Gets or sets the media type used by the responses.
Expand Down Expand Up @@ -69,10 +69,10 @@ public OpenApiProblemResponsesOptions()
/// The schema names used by
/// <see cref="ProblemResponseReplacementMode.WhenContentMatchesProblemDetails"/> to
/// decide whether an existing response already describes a problem. The collection
/// contains <c>ProblemDetails</c> and <c>ValidationProblemDetails</c> by default.
/// contains <c>CoreProblemDetails</c>, <c>ProblemDetails</c> and <c>ValidationProblemDetails</c> by default.
/// </value>
public IList<string> ProblemSchemaIds { get; } =
new List<string> { "ProblemDetails", "ValidationProblemDetails" };
new List<string> { "CoreProblemDetails", "ProblemDetails", "ValidationProblemDetails" };

/// <summary>
/// Gets the response catalog.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

namespace Core.OpenApi.Swashbuckle.IntegrationTests;

[Collection("ProcessEnvironment")]
public class OpenApiRegistrationCoverageTests
{
[Fact]
Expand Down Expand Up @@ -40,6 +41,35 @@ public void AddCoreOpenApi_DevelopmentUrlsAndBearerAndServers()
}
}

[Fact]
public void AddCoreOpenApi_DevelopmentSkipsWildcardListenAddresses()
{
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
Environment.SetEnvironmentVariable("ASPNETCORE_URLS", "http://+:8080;http://*:9000;http://0.0.0.0:80;http://[::]:8081;http://localhost:5000");

try
{
var services = new ServiceCollection();
services.AddLogging();
services.AddRouting();
var env = new FakeWebHostEnvironment();
services.AddSingleton<IWebHostEnvironment>(env);
services.AddSingleton<Microsoft.Extensions.Hosting.IHostEnvironment>(env);
services.AddCoreOpenApi();

var provider = services.BuildServiceProvider();
var document = provider.GetRequiredService<ISwaggerProvider>().GetSwagger("v1");

Assert.Contains(document.Servers, server => server.Url == "http://localhost:5000");
Assert.DoesNotContain(document.Servers, server => server.Url.Contains('+') || server.Url.Contains('*') || server.Url.Contains("0.0.0.0") || server.Url.Contains("[::]"));
}
finally
{
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", null);
Environment.SetEnvironmentVariable("ASPNETCORE_URLS", null);
}
}

[Fact]
public void AddCoreOpenApi_ConfigureCallbackAndXmlComments()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

namespace Core.OpenApi.Swashbuckle.IntegrationTests;

[Collection("ProcessEnvironment")]
public class OpenApiRegistrationTests
{
[Fact]
Expand Down
Loading