Skip to content

Commit

Permalink
1. Updated BuilderExtensions.cs to add null check in `AddSwaggerEnd…
Browse files Browse the repository at this point in the history
…Points` method and commented the exception being thrown when Swagger endpoints are null.

2. Added MMLib.ServiceDiscovery.Consul project for Consul Auto discovery clients who don't use SwaggerEndpoints in their ocelot.json file

3. Updated `MMLib.SwaggerForOcelot` in `ServiceCollectionExtensions`: Modified `AddSwaggerForOcelot` method to include conditional logic for Consul integration.

4. ConsulSwaggerEndpointProvider added if type is Consul or PollConsul. It gets Endpoints from Consul
  • Loading branch information
rabdulatif committed Oct 15, 2024
1 parent 68e34af commit da22005
Show file tree
Hide file tree
Showing 27 changed files with 856 additions and 77 deletions.
24 changes: 24 additions & 0 deletions MMLib.SwaggerForOcelot.sln
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ApiGatewayWithEndpointInter
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MMLib.SwaggerForOcelot.BenchmarkTests", "tests\MMLib.SwaggerForOcelot.BenchmarkTests\MMLib.SwaggerForOcelot.BenchmarkTests.csproj", "{BFB72205-5F70-474B-BC43-6C0B71C39FFA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MMLib.ServiceDiscovery.Consul", "src\MMLib.ServiceDiscovery.Consul\MMLib.ServiceDiscovery.Consul.csproj", "{3935ABE3-B9AF-4BDB-8621-A59D49BF84ED}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ConsulAutoDiscovery", "ConsulAutoDiscovery", "{A91B5036-2064-4C83-B379-5AD8420C4A41}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsulApiGateway", "demo\ConsulAutoDiscovery\ConsulApiGateway\ConsulApiGateway.csproj", "{BC60A6E1-1844-4133-B0F4-DD26DD84E517}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoDiscoveryApi", "demo\ConsulAutoDiscovery\AutoDiscoveryApi\AutoDiscoveryApi.csproj", "{FDF51FDB-5D75-42E0-9FC1-193C222C624C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -75,6 +83,18 @@ Global
{BFB72205-5F70-474B-BC43-6C0B71C39FFA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BFB72205-5F70-474B-BC43-6C0B71C39FFA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BFB72205-5F70-474B-BC43-6C0B71C39FFA}.Release|Any CPU.Build.0 = Release|Any CPU
{3935ABE3-B9AF-4BDB-8621-A59D49BF84ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3935ABE3-B9AF-4BDB-8621-A59D49BF84ED}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3935ABE3-B9AF-4BDB-8621-A59D49BF84ED}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3935ABE3-B9AF-4BDB-8621-A59D49BF84ED}.Release|Any CPU.Build.0 = Release|Any CPU
{BC60A6E1-1844-4133-B0F4-DD26DD84E517}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BC60A6E1-1844-4133-B0F4-DD26DD84E517}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BC60A6E1-1844-4133-B0F4-DD26DD84E517}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BC60A6E1-1844-4133-B0F4-DD26DD84E517}.Release|Any CPU.Build.0 = Release|Any CPU
{FDF51FDB-5D75-42E0-9FC1-193C222C624C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FDF51FDB-5D75-42E0-9FC1-193C222C624C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FDF51FDB-5D75-42E0-9FC1-193C222C624C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FDF51FDB-5D75-42E0-9FC1-193C222C624C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -90,6 +110,10 @@ Global
{DF18713F-3BE4-4300-BB41-D8239AAC2CA4} = {75938D16-D280-4200-A970-8D33B719D252}
{4CF0F59A-E155-4F68-B47B-7042E5A1CB2B} = {75938D16-D280-4200-A970-8D33B719D252}
{BFB72205-5F70-474B-BC43-6C0B71C39FFA} = {A9111054-B663-41BA-AE67-E6FE3E7515AF}
{3935ABE3-B9AF-4BDB-8621-A59D49BF84ED} = {D0CA2BCE-C362-4C5A-8AC9-319742DDCDD8}
{A91B5036-2064-4C83-B379-5AD8420C4A41} = {75938D16-D280-4200-A970-8D33B719D252}
{BC60A6E1-1844-4133-B0F4-DD26DD84E517} = {A91B5036-2064-4C83-B379-5AD8420C4A41}
{FDF51FDB-5D75-42E0-9FC1-193C222C624C} = {A91B5036-2064-4C83-B379-5AD8420C4A41}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {AAA408E9-E738-4F2B-A6C2-B35AAADDB00F}
Expand Down
18 changes: 18 additions & 0 deletions demo/ConsulAutoDiscovery/AutoDiscoveryApi/AutoDiscoveryApi.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.4"/>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\src\MMLib.ServiceDiscovery.Consul\MMLib.ServiceDiscovery.Consul.csproj" />
</ItemGroup>

</Project>
50 changes: 50 additions & 0 deletions demo/ConsulAutoDiscovery/AutoDiscoveryApi/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using MMLib.ServiceDiscovery.Consul.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.AddConsulAutoServiceDiscovery("http://localhost:8500"); //This line added

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseSwaggerForOcelotUI(); //This line added

var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();

app.Run("http://localhost:7002");

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions demo/ConsulAutoDiscovery/AutoDiscoveryApi/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
18 changes: 18 additions & 0 deletions demo/ConsulAutoDiscovery/ConsulApiGateway/ConsulApiGateway.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.4"/>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0"/>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\src\MMLib.SwaggerForOcelot\MMLib.SwaggerForOcelot.csproj" />
</ItemGroup>

</Project>
25 changes: 25 additions & 0 deletions demo/ConsulAutoDiscovery/ConsulApiGateway/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Ocelot.DependencyInjection;
using Ocelot.Provider.Consul;
using Ocelot.Middleware;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();

builder.Configuration
.SetBasePath(builder.Environment.ContentRootPath)
.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();

builder.Services
.AddOcelot(builder.Configuration)
.AddConsul();

builder.Services.AddSwaggerForOcelot(builder.Configuration);

var app = builder.Build();

app.UseSwaggerForOcelotUI();
await app.UseOcelot();

app.MapGet("/", () => "Hello World!").WithOpenApi();
app.Run("http://0.0.0.0:7001");
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions demo/ConsulAutoDiscovery/ConsulApiGateway/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
14 changes: 14 additions & 0 deletions demo/ConsulAutoDiscovery/ConsulApiGateway/ocelot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"Routes": [],
"SwaggerEndPoints": [],
"GlobalConfiguration": {
"ServiceDiscoveryProvider": {
"Scheme": "http",
"Host": "localhost",
"Port": 8500,
"Type": "PollConsul",
"PollingInterval": 100
}
}
}

4 changes: 4 additions & 0 deletions demo/OrderService/OrderService.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,9 @@
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\MMLib.ServiceDiscovery.Consul\MMLib.ServiceDiscovery.Consul.csproj" />
</ItemGroup>


</Project>
36 changes: 28 additions & 8 deletions demo/OrderService/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.PlatformAbstractions;
using MMLib.ServiceDiscovery.Consul.DependencyInjection;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.IO;
using System.Reflection;
Expand Down Expand Up @@ -67,6 +67,7 @@ public void ConfigureServices(IServiceCollection services)
// integrate xml comments
options.IncludeXmlComments(XmlCommentsFilePath);
});

}

/// <summary>
Expand All @@ -79,15 +80,34 @@ public void Configure(IApplicationBuilder app, IApiVersionDescriptionProvider pr
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
app.UseSwagger();
_ = app.UseSwaggerUI(
options =>
// _ = app.UseSwaggerUI(
// options =>
// {
// // build a swagger endpoint for each discovered API version
// foreach (ApiVersionDescription description in provider.ApiVersionDescriptions)
// {
// options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
// }
// });
app.UseSwaggerUI(c =>
{
c.RoutePrefix = "swagger";
foreach (var description in provider.ApiVersionDescriptions)
{
c.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", $"Version {description.GroupName}");
}
});

// Separate endpoints that contain only one version
foreach (var description in provider.ApiVersionDescriptions)
{
app.UseSwaggerUI(c =>
{
// build a swagger endpoint for each discovered API version
foreach (ApiVersionDescription description in provider.ApiVersionDescriptions)
{
options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
}
c.RoutePrefix = $"swagger/{description.GroupName}";
c.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", $"Version {description.GroupName}");
});
}

}

static string XmlCommentsFilePath
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.SwaggerUI;

namespace MMLib.ServiceDiscovery.Consul.DependencyInjection;

/// <summary>
///
/// </summary>
public static class ConfigureExtensions
{
/// <summary>
///
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IApplicationBuilder UseSwaggerForOcelotUI(this WebApplication builder)
{
builder.ConfigureConsulConnection();
builder.MapHealthChecks("/api/health");

return builder;
}

/// <summary>
///
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IApplicationBuilder ConfigureConsulConnection(this IApplicationBuilder builder)
{
var consul = builder.ApplicationServices.GetService<IConsulConnectionService>();
consul?.Start();

return builder;
}
}
Loading

0 comments on commit da22005

Please sign in to comment.