### Install MMLib.SwaggerForOcelot via NuGet Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Use the dotnet CLI to add the MMLib.SwaggerForOcelot package to your Ocelot gateway project. ```bash dotnet add package MMLib.SwaggerForOcelot ``` -------------------------------- ### Ocelot Configuration for Aggregates Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Example Ocelot configuration defining routes, parameter mapping for aggregation, and an aggregate route with a custom description. ```json // ocelot.json — aggregate route with custom description and parameter map { "Routes": [ { "DownstreamPathTemplate": "/api/user/{id}", "ServiceName": "user", "UpstreamPathTemplate": "/gateway/api/user/{id}", "SwaggerKey": "user", "Key": "user" }, { "DownstreamPathTemplate": "/api/basket/{buyerId}", "ServiceName": "basket", "UpstreamPathTemplate": "/gateway/api/basket/{id}", "SwaggerKey": "basket", "Key": "basket", "ParametersMap": { "id": "buyerId" } } ], "Aggregates": [ { "RouteKeys": [ "user", "basket" ], "UpstreamPathTemplate": "/gateway/api/basketwithuser/{id}", "Description": "Returns user profile combined with their basket.", "Aggregator": "BasketAggregator" } ] } ``` -------------------------------- ### Configure Ocelot with Split Configuration Files and Swagger Support Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Load Ocelot configuration from multiple files while keeping SwaggerEndPoints in a dedicated file. This method merges all matching files before the host starts. ```csharp // Program.cs WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { config.AddOcelotWithSwaggerSupport(o => { // Folder that contains ocelot.*.json files o.Folder = "Configuration"; // File with SwaggerEndPoints section (without .json extension) o.FileOfSwaggerEndPoints = "ocelot.SwaggerEndPoints"; // Filter files to current environment (e.g. only ocelot.*.Production.json) o.Environment = hostingContext.HostingEnvironment; // Override the merged output file name (default: ocelot.json) o.PrimaryOcelotConfigFile = "gateway.json"; }); }) .UseStartup() .Build() .Run(); ``` -------------------------------- ### Ocelot Route with Authentication Configuration Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Example of an Ocelot route configuration with authentication options. The AuthenticationProviderKey is mapped to a Swagger scheme name for UI display. ```json // ocelot.json — route with authentication { "Routes": [ { "DownstreamPathTemplate": "/api/{everything}", "ServiceName": "projects", "UpstreamPathTemplate": "/api/project/{everything}", "SwaggerKey": "projects", "AuthenticationOptions": { "AuthenticationProviderKey": "Bearer", "AllowedScopes": [ "projects.read", "projects.write" ] } } ] } // Result in transformed OpenAPI: // "security": [{ "appAuth": ["projects.read", "projects.write"] }] ``` -------------------------------- ### Generated Security Definitions in Swagger Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Example of how security definitions appear in the generated Swagger document based on the provided configuration. ```json { "paths": { "/api/project": { "get": { ... "security": [ { "appAuth": [ "scope" ] } ] } } } } ``` -------------------------------- ### Implement Downstream Swagger Interceptor Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Implement the ISwaggerDownstreamInterceptor interface to control which downstream Swagger endpoints are exposed. This example hides unpublished documentation. ```csharp // Implementation public class PublishedDownstreamInterceptor : ISwaggerDownstreamInterceptor { private readonly ISwaggerEndpointConfigurationRepository _repo; public PublishedDownstreamInterceptor(ISwaggerEndpointConfigurationRepository repo) => _repo = repo; public bool DoDownstreamSwaggerEndpoint(HttpContext context, string version, SwaggerEndPointOptions endPoint) { var config = _repo.GetSwaggerEndpoint(endPoint, version); if (!config.IsPublished) { context.Response.StatusCode = StatusCodes.Status404NotFound; context.Response.WriteAsync($"The '{endPoint.Key}' {version} docs are not yet published."); return false; // abort — response already written } return true; // proceed with downstream fetch } } ``` ```csharp // Registration in Program.cs builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSwaggerForOcelot(builder.Configuration); ``` -------------------------------- ### Implement Downstream Swagger Interceptor Logic Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Implement the `DoDownstreamSwaggerEndpoint` method in your custom interceptor to conditionally control whether downstream calls to Swagger endpoints are made. This example returns a 404 if the endpoint is not published. ```csharp public class PublishedDownstreamInterceptor : ISwaggerDownstreamInterceptor { private readonly ISwaggerEndpointConfigurationRepository _endpointConfigurationRepository; public PublishedDownstreamInterceptor(ISwaggerEndpointConfigurationRepository endpointConfigurationRepository) { _endpointConfigurationRepository = endpointConfigurationRepository; } public bool DoDownstreamSwaggerEndpoint(HttpContext httpContext, string version, SwaggerEndPointOptions endPoint) { var myEndpointConfiguration = _endpointConfigurationRepository.GetSwaggerEndpoint(endPoint, version); if (!myEndpointConfiguration.IsPublished) { httpContext.Response.StatusCode = 404; httpContext.Response.WriteAsync("This enpoint is under development, please come back later."); } return myEndpointConfiguration.IsPublished; } } ``` -------------------------------- ### Enable Gateway Documentation Generation (C#) Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md To generate documentation for the gateway itself, set `GenerateDocsForGatewayItSelf` to `true` during the `AddSwaggerForOcelot` configuration. This allows for documenting gateway-specific controllers and aggregations. ```csharp services.AddSwaggerForOcelot(Configuration, (o) => { o.GenerateDocsForGatewayItSelf = true; }); ``` -------------------------------- ### Enable Downstream Documentation Caching Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Configure caching for downstream documentation in your Startup class to improve response times for large documentation sets. The cache will refresh if the downstream documentation changes. ```csharp services.AddSwaggerForOcelot(Configuration, setup => { setup.DownstreamDocsCacheExpire = TimeSpan.FromMinutes(10); }); ``` -------------------------------- ### Configure SwaggerForOcelot UI Middleware Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Add the SwaggerForOcelot middleware to the request pipeline and configure SwaggerUI to point to the gateway's documentation endpoint. This is done in `Program.cs` or `Startup.Configure`. ```csharp var app = builder.Build(); app.UseRouting(); await app.UseOcelot(); // Minimal usage — exposes UI at /swagger and docs at /swagger/docs app.UseSwaggerForOcelotUI(opt => { opt.PathToSwaggerGenerator = "/swagger/docs"; // default // Forward headers to downstream swagger endpoints (e.g. for auth) opt.DownstreamSwaggerHeaders = new[] { new KeyValuePair("Authorization", "Bearer "), }; // Optionally override the gateway server prefix shown in Swagger UI opt.ServerOcelot = "/mysite/apigateway"; // Post-process the transformed upstream Swagger JSON synchronously opt.ReConfigureUpstreamSwaggerJson = (httpContext, swaggerJson) => { var doc = JObject.Parse(swaggerJson); doc["info"]!["x-custom"] = "injected"; return doc.ToString(Formatting.Indented); }; // Or asynchronously opt.ReConfigureUpstreamSwaggerJsonAsync = async (httpContext, swaggerJson) => { await Task.Delay(0); // async work return swaggerJson; }; }, uiOpt => { // Configure Swashbuckle SwaggerUI options directly uiOpt.DocumentTitle = "My Gateway API"; }); await app.RunAsync(); ``` -------------------------------- ### Map AuthenticationProviderKey in Startup Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Register authentication provider key mappings in your application's Startup class to link Ocelot authentication with Swagger security definitions. ```csharp services.AddSwaggerForOcelot(Configuration, (o) => { o.AddAuthenticationProviderKeyMapping("Bearer", "appAuth"); }); ``` -------------------------------- ### Enable Aggregate Documentation in Services Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Configure Ocelot services to generate documentation for aggregates by setting `GenerateDocsForAggregates` to true. ```csharp services.AddSwaggerForOcelot(Configuration, (o) => { o.GenerateDocsForAggregates = true; }); ``` -------------------------------- ### Customize Server Path and Swagger UI Options Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Optionally set the Ocelot server path and customize Swagger UI options like the document title. ```csharp app.UseSwaggerForOcelotUI(opt => { // swaggerForOcelot options }, uiOpt => { //swaggerUI options uiOpt.DocumentTitle = "Gateway documentation"; }) ``` -------------------------------- ### Advanced Gateway Documentation Configuration (C#) Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Configure advanced options for gateway documentation, including XML comment file paths, gateway title, OpenAPI info, document filters, and security definitions like Bearer tokens. ```csharp services.AddSwaggerForOcelot(Configuration, (o) => { o.GenerateDocsDocsForGatewayItSelf(opt => { opt.FilePathsForXmlComments = { "MyAPI.xml" }; opt.GatewayDocsTitle = "My Gateway"; opt.GatewayDocsOpenApiInfo = new() { Title = "My Gateway", Version = "v1", }; opt.DocumentFilter(); opt.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Bearer" }); opt.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header, }, new List() } }); }); }); ``` -------------------------------- ### Use Swagger Generator in Configure Section (C#) Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Enable the Swagger UI middleware in the `Configure` section of your application's startup to serve the generated API documentation. ```csharp app.UseSwagger(); ``` -------------------------------- ### Register SwaggerForOcelot Service Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Add the SwaggerForOcelot service to the dependency injection container in your Startup.cs. ```csharp services.AddSwaggerForOcelot(Configuration); ``` -------------------------------- ### Post-process Aggregate Documentation Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Customize the generated aggregate documentation by providing a post-processor function to `AggregateDocsGeneratorPostProcess` during service configuration. This allows for modifications like adding custom parameters. ```csharp services.AddSwaggerForOcelot(Configuration, (o) => { o.GenerateDocsForAggregates = true; o.AggregateDocsGeneratorPostProcess = (aggregateRoute, routesDocs, pathItemDoc, documentation) => { if (aggregateRoute.UpstreamPathTemplate == "/gateway/api/basketwithuser/{id}") { pathItemDoc.Operations[OperationType.Get].Parameters.Add(new OpenApiParameter() { Name = "customParameter", Schema = new OpenApiSchema() { Type = "string"}, In = ParameterLocation.Header }); } }; }); ``` -------------------------------- ### Configure Environment-Specific Swagger Endpoints Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Enable environment-specific configuration files for Ocelot and Swagger endpoints by setting the `Folder` and `Environment` options. ```csharp WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { config.AddOcelotWithSwaggerSupport((o) => { o.Folder = "Configuration"; o.Environment = hostingContext.HostingEnvironment; }); }) .UseStartup(); ``` -------------------------------- ### Enable Swagger for Ocelot Aggregates Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Configure Swagger generation for Ocelot request aggregation routes in Startup/Program.cs. Supports custom descriptions and parameter mapping via Ocelot configuration. Optionally, post-process generated aggregate documentation. ```csharp // Startup / Program.cs builder.Services.AddSwaggerForOcelot(builder.Configuration, o => { o.GenerateDocsForAggregates = true; // Optional: post-process generated aggregate path items o.AggregateDocsGeneratorPostProcess = (aggregateRoute, routesDocs, pathItemDoc, documentation) => { if (aggregateRoute.UpstreamPathTemplate == "/gateway/api/basketwithuser/{id}") { pathItemDoc.Operations[OperationType.Get].Parameters.Add(new OpenApiParameter { Name = "X-Correlation-ID", Schema = new OpenApiSchema { Type = "string" }, In = ParameterLocation.Header, Required = false }); } }; }); ``` -------------------------------- ### Register SwaggerForOcelot Services Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Register the necessary services for SwaggerForOcelot in the ASP.NET Core DI container. This is typically done in `Program.cs` or `Startup.ConfigureServices`. ```csharp // Program.cs (minimal hosting model) var builder = WebApplication.CreateBuilder(args); builder.Configuration.AddJsonFile("ocelot.json"); builder.Services.AddOcelot(builder.Configuration); // Basic registration builder.Services.AddSwaggerForOcelot(builder.Configuration); ``` ```csharp // --- OR with full options --- builder.Services.AddSwaggerForOcelot(builder.Configuration, ocelotSwaggerSetup: o => { // Generate docs for Ocelot aggregates (shows on "Aggregates" page) o.GenerateDocsForAggregates = true; // Generate docs for controllers hosted directly on the gateway o.GenerateDocsForGatewayItSelf = true; // Cache transformed downstream docs for 10 minutes o.DownstreamDocsCacheExpire = TimeSpan.FromMinutes(10); // Map Ocelot authentication provider keys to Swagger security schemes o.AddAuthenticationProviderKeyMapping("Bearer", "appAuth"); }); ``` -------------------------------- ### Add SwaggerForOcelot UI Middleware Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Insert the SwaggerForOcelot UI middleware in the Configure method to expose the interactive documentation endpoint. ```csharp app.UseSwaggerForOcelotUI(opt => { opt.PathToSwaggerGenerator = "/swagger/docs"; }) ``` -------------------------------- ### Gateway Self-Documentation with Security Definitions Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Configures Swagger for Ocelot to expose documentation for gateway-specific controllers. Supports custom titles, OpenAPI info, XML comments, document filters, and security definitions like Bearer tokens. ```csharp builder.Services.AddSwaggerForOcelot(builder.Configuration, o => { o.GenerateDocsDocsForGatewayItSelf(opt => { opt.GatewayDocsTitle = "My Gateway"; opt.GatewayDocsOpenApiInfo = new OpenApiInfo { Title = "My Gateway", Version = "v1", Description = "Gateway-level API endpoints" }; // Include XML comments from gateway project opt.FilePathsForXmlComments = new[] { "MyGateway.xml" }; // Add custom document filters opt.DocumentFilter(); // Add Bearer security definition opt.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header. Example: 'Bearer {token}'", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Bearer" }); opt.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, new List() } }); }); }); // Also register Swashbuckle's own middleware so gateway docs are generated app.UseSwagger(); app.UseSwaggerForOcelotUI(); ``` -------------------------------- ### Configure Swagger Endpoints Folder Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Specify a custom folder for Ocelot configuration files, including the Swagger endpoints file, by setting the `Folder` option. ```csharp WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { config.AddOcelotWithSwaggerSupport((o) => { o.Folder = "Configuration"; }); }) .UseStartup(); ``` -------------------------------- ### Configure Primary Ocelot Config File Name Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Set a custom name for the primary Ocelot configuration file (default is 'ocelot.json') using the `PrimaryOcelotConfigFile` option. ```csharp WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { config.AddOcelotWithSwaggerSupport((o) => { o.PrimaryOcelotConfigFile = "myOcelot.json"; }); }) .UseStartup(); ``` -------------------------------- ### Configure Ocelot.json for SwaggerForOcelot Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Define routes and Swagger endpoints in ocelot.json. The 'SwaggerKey' in routes pairs with 'Key' in SwaggerEndPoints to link Ocelot routes to their respective Swagger definitions. ```json { "Routes": [ { "DownstreamPathTemplate": "/api/{everything}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5100 } ], "UpstreamPathTemplate": "/api/contacts/{everything}", "UpstreamHttpMethod": [ "Get" ], "SwaggerKey": "contacts" }, { "DownstreamPathTemplate": "/api/{everything}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5200 } ], "UpstreamPathTemplate": "/api/orders/{everything}", "UpstreamHttpMethod": [ "Get" ], "SwaggerKey": "orders" } ], "SwaggerEndPoints": [ { "Key": "contacts", "Config": [ { "Name": "Contacts API", "Version": "v1", "Url": "http://localhost:5100/swagger/v1/swagger.json" } ] }, { "Key": "orders", "Config": [ { "Name": "Orders API", "Version": "v0.9", "Url": "http://localhost:5200/swagger/v0.9/swagger.json" }, { "Name": "Orders API", "Version": "v1", "Url": "http://localhost:5200/swagger/v1/swagger.json" }, { "Name": "Orders API", "Version": "v2", "Url": "http://localhost:5200/swagger/v2/swagger.json" }, { "Name": "Orders API", "Version": "v3", "Url": "http://localhost:5200/swagger/v3/swagger.json" } ] } ], "GlobalConfiguration": { "BaseUrl": "http://localhost" } } ``` -------------------------------- ### Add Ocelot with Swagger Support Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Use this extension to enable Ocelot with Swagger support, allowing configuration from multiple files. The default swagger endpoints file is 'ocelot.SwaggerEndPoints.json'. ```csharp WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { config.AddOcelotWithSwaggerSupport(); }) .UseStartup(); ``` -------------------------------- ### Ocelot Configuration with Virtual Directory Support Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Configures Ocelot to handle downstream services hosted under a virtual directory. Set `VirtualDirectory` on the route to strip the virtual prefix from downstream paths. ```json { "Routes": [ { "DownstreamPathTemplate": "/project/api/{everything}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [{ "Host": "localhost", "Port": 5100 }], "UpstreamPathTemplate": "/api/project/{everything}", "UpstreamHttpMethod": [ "Get" ], "SwaggerKey": "project", "VirtualDirectory": "/project" } ], "SwaggerEndPoints": [ { "Key": "project", "Config": [ { "Name": "Projects API", "Version": "v1", "Url": "http://localhost:5100/project/swagger/v1/swagger.json" } ] } ] } ``` -------------------------------- ### Ocelot Service Discovery Integration (Consul) Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Integrates Ocelot with a service discovery provider like Consul. Specify the service name and swagger path within a `Service` object instead of a hard-coded URL. ```json { "Routes": [ { "DownstreamPathTemplate": "/api/{everything}", "ServiceName": "orders", "UpstreamPathTemplate": "/api/orders/{everything}", "SwaggerKey": "orders" } ], "SwaggerEndPoints": [ { "Key": "orders", "Config": [ { "Name": "Orders API", "Version": "v1", "Service": { "Name": "orders", "Path": "/swagger/v1/swagger.json" } } ] } ], "GlobalConfiguration": { "ServiceDiscoveryProvider": { "Type": "Consul", "Host": "localhost", "Port": 8500, "PollingInterval": 1000 } } } ``` -------------------------------- ### Ocelot Core Configuration with Swagger Integration Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Defines Ocelot routes and links them to Swagger endpoints using SwaggerKey. Ensure SwaggerKey on routes matches keys in SwaggerEndPoints for correct path rewriting. ```json { "Routes": [ { "DownstreamPathTemplate": "/api/{everything}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [{ "Host": "localhost", "Port": 5100 }], "UpstreamPathTemplate": "/api/contacts/{everything}", "UpstreamHttpMethod": [ "Get", "Post", "Put", "Delete" ], "SwaggerKey": "contacts" }, { "DownstreamPathTemplate": "/api/{everything}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [{ "Host": "localhost", "Port": 5200 }], "UpstreamPathTemplate": "/api/orders/{everything}", "UpstreamHttpMethod": [ "Get", "Post" ], "SwaggerKey": "orders" } ], "SwaggerEndPoints": [ { "Key": "contacts", "Config": [ { "Name": "Contacts API", "Version": "v1", "Url": "http://localhost:5100/swagger/v1/swagger.json" } ] }, { "Key": "orders", "Config": [ { "Name": "Orders API", "Version": "v1", "Url": "http://localhost:5200/swagger/v1/swagger.json" }, { "Name": "Orders API", "Version": "v2", "Url": "http://localhost:5200/swagger/v2/swagger.json" } ] } ], "GlobalConfiguration": { "BaseUrl": "http://localhost:8080" } } ``` -------------------------------- ### Configure Virtual Directory for Downstream Service Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md When a downstream service is hosted in a virtual directory, set the `VirtualDirectory` property to the virtual directory path to ensure correct path transformation for upstream requests. ```json { "DownstreamPathTemplate": "/project/api/{everything}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5100 } ], "UpstreamPathTemplate": "/api/project/{everything}", "UpstreamHttpMethod": [ "Get" ], "SwaggerKey": "project", "VirtualDirectory":"/project" } ``` -------------------------------- ### Add AuthenticationOptions to Route Definition Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Configure authentication providers and allowed scopes within your Ocelot route definitions. ```json "Routes": [ { "DownstreamPathTemplate": "/api/{everything}", "ServiceName": "projects", "UpstreamPathTemplate": "/api/project/{everything}", "SwaggerKey": "projects", "AuthenticationOptions": { "AuthenticationProviderKey": "Bearer", "AllowedScopes": [ "scope" ] }, } ] ``` -------------------------------- ### Map Downstream Parameter Names Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Use the `ParametersMap` property in Ocelot configuration to map Ocelot's upstream parameter names to different downstream parameter names, ensuring correct documentation generation. ```json { "DownstreamPathTemplate": "/api/basket/{id}", "UpstreamPathTemplate": "/gateway/api/basket/{id}", "ParametersMap": { "id": "buyerId" }, "ServiceName": "basket", "SwaggerKey": "basket", "Key": "basket" } ``` -------------------------------- ### Configure Custom Swagger Endpoints File Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Customize the name of the file containing Swagger endpoint settings by providing a custom name (without the .json extension) to the `FileOfSwaggerEndPoints` option. ```csharp WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { config.AddOcelotWithSwaggerSupport((o) => { o.FileOfSwaggerEndPoints = "ocelot.swagger"; }) }) .UseStartup(); ``` -------------------------------- ### Custom Ocelot Aggregator with Response Documentation Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Implement a custom aggregator to combine responses from multiple downstream services and document the combined response structure. Requires defining DTOs for the combined response. ```csharp // Custom aggregator with response documentation [AggregateResponse("Combined user and basket response.", typeof(BasketWithUserResponse))] public class BasketAggregator : IDefinedAggregator { public async Task Aggregate(List responses) { var userJson = await responses[0].Items.DownstreamResponse().Content.ReadAsStringAsync(); var basketJson = await responses[1].Items.DownstreamResponse().Content.ReadAsStringAsync(); var combined = new BasketWithUserResponse { User = JsonSerializer.Deserialize(userJson), Basket = JsonSerializer.Deserialize(basketJson) }; var content = new StringContent(JsonSerializer.Serialize(combined), Encoding.UTF8, "application/json"); return new DownstreamResponse(content, HttpStatusCode.OK, new List
(), "OK"); } } ``` -------------------------------- ### Enable Taking Servers From Downstream Service Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Set `TakeServersFromDownstreamService` to `true` in `SwaggerEndPoints` to use server definitions from the downstream service's Open API documentation. This is useful when multiple servers are defined or server templating is used. ```json "SwaggerEndPoints": [ { "Key": "users", "TakeServersFromDownstreamService": true, "Config": [ { "Name": "Users API", "Version": "v1", "Service": { "Name": "users", "Path": "/swagger/v1/swagger.json" } } ] } ] ``` -------------------------------- ### Map Ocelot AuthenticationProviderKey to Swagger Security Scheme Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Map Ocelot AuthenticationProviderKey values to Swagger security scheme names. This ensures protected endpoints display the correct security badge in Swagger UI. ```csharp builder.Services.AddSwaggerForOcelot(builder.Configuration, o => { // "Bearer" is the Ocelot AuthenticationProviderKey; "appAuth" is the Swagger scheme name o.AddAuthenticationProviderKeyMapping("Bearer", "appAuth"); }); ``` -------------------------------- ### Register Downstream Interceptor and Repository Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Register your custom `ISwaggerDownstreamInterceptor` and `ISwaggerEndpointConfigurationRepository` implementations in the `ConfigureServices` method to control downstream API calls. ```csharp services.AddSingleton(); services.AddSingleton(); ``` -------------------------------- ### Enable Downstream Docs Caching Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Enable in-memory caching of transformed Swagger JSON. The cache is keyed by a SHA-256 hash of the raw downstream JSON, automatically invalidating when upstream content changes. ```csharp builder.Services.AddSwaggerForOcelot(builder.Configuration, setup => { setup.DownstreamDocsCacheExpire = TimeSpan.FromMinutes(10); }); ``` -------------------------------- ### Configure Downstream Swagger Headers Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Optionally configure headers to be sent with requests to downstream swagger endpoints, useful for authentication. ```csharp app.UseSwaggerForOcelotUI(opt => { opt.DownstreamSwaggerHeaders = new[] { new KeyValuePair("Auth-Key", "AuthValue"), }; }) ``` -------------------------------- ### Pass Through OpenAPI Servers Definition Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Forward the server list unchanged when a downstream service defines multiple servers or uses server templating in its OpenAPI 3.0 spec. Path transformation is skipped in this mode. ```json { "SwaggerEndPoints": [ { "Key": "users", "TakeServersFromDownstreamService": true, "Config": [ { "Name": "Users API", "Version": "v1", "Service": { "Name": "users", "Path": "/swagger/v1/swagger.json" } } ] } ] } ``` -------------------------------- ### Reconfigure Upstream Swagger JSON Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Customize the upstream Swagger JSON before it's exposed by providing a synchronous or asynchronous re-configuration method. ```csharp public string AlterUpstreamSwaggerJson(HttpContext context, string swaggerJson) { var swagger = JObject.Parse(swaggerJson); // ... alter upstream json return swagger.ToString(Formatting.Indented); } app.UseSwaggerForOcelotUI(opt => { opt.ReConfigureUpstreamSwaggerJson = AlterUpstreamSwaggerJson; }) ``` -------------------------------- ### Custom Aggregate Description in ocelot.json Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Provide a custom description for an aggregate route by adding the `Description` property within the `Aggregates` section of your `ocelot.json` configuration. ```json "Aggregates": [ { "RouteKeys": [ "user", "basket" ], "Description": "Custom description for this aggregate route.", "Aggregator": "BasketAggregator", "UpstreamPathTemplate": "/gateway/api/basketwithuser/{id}" } ] ``` -------------------------------- ### Integrate Service Discovery with Swagger Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md When using Ocelot Service Discovery, you can reference the downstream service by its name in the Swagger configuration. Ensure the `ServiceName` in the route matches the service name used for swagger configuration. ```json "Routes": [ { "DownstreamPathTemplate": "/api/{everything}", "ServiceName": "projects", "UpstreamPathTemplate": "/api/project/{everything}", "SwaggerKey": "projects", } ], "SwaggerEndPoints": [ { "Key": "projects", "Config": [ { "Name": "Projects API", "Version": "v1", "Service": { "Name": "projects", "Path": "/swagger/v1/swagger.json" } } ] } ], "GlobalConfiguration": { "ServiceDiscoveryProvider": { "Type": "AppConfiguration", "PollingInterval": 1000 } } ``` -------------------------------- ### Disable Removal of Unused Schema Components Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Configure Swagger for Ocelot to prevent the removal of unused schema components from downstream documentation, which can be useful for very large documentation sets. ```json "SwaggerEndPoints": [ { "Key": "projects", "RemoveUnusedComponentsFromScheme": false, "Config": [ { "Name": "Projects API", "Version": "v1", "Service": { "Name": "projects", "Path": "/swagger/v1/swagger.json" } } ] } ] ``` -------------------------------- ### Custom Aggregate Response Attribute Source: https://github.com/burgyn/mmlib.swaggerforocelot/blob/master/README.md Use the `AggregateResponseAttribute` on a custom aggregator class to define the response documentation when using custom `IDefinedAggregator` implementations. ```csharp [AggregateResponse("Basket with buyer and busket items.", typeof(CustomResponse))] public class BasketAggregator : IDefinedAggregator { public async Task Aggregate(List responses) { ... } } ``` -------------------------------- ### Disable Unused Component Removal for Large Swagger Documents Source: https://context7.com/burgyn/mmlib.swaggerforocelot/llms.txt Disable the component-cleanup pass for individual endpoints when dealing with very large Swagger documents (>10 MB) to improve performance. ```json { "SwaggerEndPoints": [ { "Key": "bigservice", "RemoveUnusedComponentsFromScheme": false, "Config": [ { "Name": "Big Service API", "Version": "v1", "Url": "http://localhost:5300/swagger/v1/swagger.json" } ] } ] } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.