For NSwag package:
Solution 1- Using PostProcess function
// config it inside program.cs
app.MapHealthChecks("/health", new() { });
builder.Services.AddHealthChecks();
builder.Services.AddSwaggerDocument(config =>
{
config.DocumentName = "Test1";
config.Title = "App API";
config.Description = "Rest API";
//config.PostProcess = document => document.Info.Version = "v1";
//config.ApiGroupNames = new[] { "v1" };
config.PostProcess = document =>
{
var pathItem = new OpenApiPathItem();
var param = new OpenApiParameter
{
Name = "key",
IsRequired = true,
Kind = OpenApiParameterKind.Query,
Description = "The key to use for the health check auth",
Schema = new NJsonSchema.JsonSchema { Type = JsonObjectType.String }
};
var operation = new OpenApiOperation
{
OperationId = "HealthCheckDetail",
Description = "Check the health of the API",
Tags = new List<string> { "Health" },
Responses =
{
{ "200", new OpenApiResponse { Description = "OK" } },
{ "401", new OpenApiResponse { Description = "Unauthorized" } },
{ "503", new OpenApiResponse { Description = "Service Unavailable" } }
},
};
// if auth is required
operation.Parameters.Add(param);
pathItem.TryAdd(OpenApiOperationMethod.Get, operation);
document.Paths.Add("/health", pathItem);
};
});
Solution 2- Using IApiDescriptionProvider
public class HealthCheckDescriptionProvider : IApiDescriptionProvider
{
private readonly IModelMetadataProvider _modelMetadataProvider;
public HealthCheckDescriptionProvider(IModelMetadataProvider modelMetadataProvider)
{
_modelMetadataProvider = modelMetadataProvider;
}
public int Order => -1;
public void OnProvidersExecuting(ApiDescriptionProviderContext context)
{ }
public void OnProvidersExecuted(ApiDescriptionProviderContext context)
{
var actionDescriptor = new ControllerActionDescriptor
{
ControllerName = "HealthChecks",
ActionName = "health",
Parameters = new List<ParameterDescriptor>(),
EndpointMetadata = new List<object>(),
ActionConstraints = new List<IActionConstraintMetadata>(),
DisplayName = "Health check endpoint",
Properties = new Dictionary<object, object?>(),
BoundProperties = new List<ParameterDescriptor>(),
FilterDescriptors = new List<FilterDescriptor>(),
ControllerTypeInfo = new TypeDelegator(typeof(string))
};
var apiDescription = new ApiDescription
{
ActionDescriptor = actionDescriptor,
HttpMethod = HttpMethods.Get,
RelativePath = "health",
GroupName = "v1",
};
var apiResponseType = new ApiResponseType
{
ApiResponseFormats = new List<ApiResponseFormat>
{
new ApiResponseFormat
{
MediaType = ("text/plain"),
Formatter = new StringOutputFormatter(),
},
},
Type = typeof(string),
StatusCode = StatusCodes.Status200OK,
};
apiDescription.SupportedResponseTypes.Add(apiResponseType);
context.Results.Add(apiDescription);
}
}
// config it inside program.cs
builder.Services.AddApiVersioning(options =>
{
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
options.ReportApiVersions = true;
});
builder.Services.AddVersionedApiExplorer(
options =>
{
options.GroupNameFormat = "'v'V";
options.SubstituteApiVersionInUrl = true;
});
builder.Services.AddSwaggerDocument(config =>
{
config.DocumentName = "A_v1";
config.Title = "A API";
config.Description = "Rest API ";
config.PostProcess = document => document.Info.Version = "v1";
config.ApiGroupNames = new[] { "v1" };
});
builder.Services.TryAddEnumerable(ServiceDescriptor.Transient<IApiDescriptionProvider, HealthCheckDescriptionProvider>());
builder.Services
.AddHealthChecks();
app.MapHealthChecks("/health", new() { });
For Swashbuckle package:
Solution 1- Using IDocumentFilter
// Create a health check filter
public class HealthChecksFilter : IDocumentFilter
{
public void Apply(OpenApiDocument openApiDocument, DocumentFilterContext context)
{
var schema = context.SchemaGenerator.GenerateSchema(typeof(HealthCheckResponse), context.SchemaRepository);
var healthyResponse = new OpenApiResponse();
healthyResponse.Content.Add("application/json", new OpenApiMediaType { Schema = schema });
healthyResponse.Description = "API service is healthy";
var unhealthyResponse = new OpenApiResponse();
unhealthyResponse.Content.Add("application/json", new OpenApiMediaType { Schema = schema });
unhealthyResponse.Description = "API service is not healthy";
var operation = new OpenApiOperation();
operation.Description = "Returns the health status of this service";
operation.Tags.Add(new OpenApiTag { Name = "Health Check API" });
operation.Responses.Add("200", healthyResponse);
operation.Responses.Add("500", unhealthyResponse);
operation.Parameters.Add(new()
{
Name = "customParam",
In = ParameterLocation.Query,
Required = false,
Description = "If this parameter is true, ....",
Schema = new()
{
Type = "boolean"
}
});
var pathItem = new OpenApiPathItem();
pathItem.AddOperation(OperationType.Get, operation);
openApiDocument?.Paths.Add("/health", pathItem);
}
// config it inside program.cs
builder.Services.AddHealthChecks();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("1.0.0", new OpenApiInfo
{
Version = "1.0.0",
Title = "Test",
Description = "Swagger definition for ....",
});
// Add that filter here
c.DocumentFilter<HealthChecksFilter>();
});
app.MapHealthChecks("/health", new() { });
}