Something went wrong. Try again.
Den is the private cloud vault for your reminders, calendars and to-dos.
Something went wrong. Try again.
6.8 kB · 170 lines
C#
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Diagnostics.HealthChecks;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Diagnostics.HealthChecks;using Microsoft.Extensions.Logging;using Microsoft.Extensions.ServiceDiscovery;using Microsoft.OpenApi.Models;using OpenTelemetry;using OpenTelemetry.Metrics;using OpenTelemetry.Trace;
#pragma warning disable IDE0130 // Namespace does not match folder structurenamespace Microsoft.Extensions.Hosting;#pragma warning restore IDE0130 // Namespace does not match folder structure
// Adds common Aspire services: service discovery, resilience, health checks, and OpenTelemetry.// This project should be referenced by each service project in your solution.// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaultspublic static class Extensions{ private const string HealthEndpointPath = "/healthz"; private const string AlivenessEndpointPath = "/livez";
public static TBuilder AddServiceDefaults<TBuilder>(this TBuilder builder, bool isApi = true) where TBuilder : IHostApplicationBuilder { builder.ConfigureOpenTelemetry();
builder.AddDefaultHealthChecks();
builder.Services.AddServiceDiscovery();
if (isApi) { builder.Services.AddOpenApi(options => { options.AddDocumentTransformer((document, context, cancellationToken) => { document.Components ??= new(); document.Components.SecuritySchemes ??= new Dictionary<string, OpenApiSecurityScheme>(); document.Components.SecuritySchemes["Bearer"] = new() { Type = SecuritySchemeType.Http, Scheme = "bearer", BearerFormat = "JWT", Description = "JWT Authorization header using the Bearer scheme" }; return Task.CompletedTask; });
options.AddOperationTransformer((operation, context, cancellationToken) => { var metadata = context.Description.ActionDescriptor.EndpointMetadata; var hasAuthorize = metadata.OfType<AuthorizeAttribute>().Any(); var hasAllowAnonymous = metadata.OfType<AllowAnonymousAttribute>().Any();
if (hasAuthorize && !hasAllowAnonymous) { operation.Security = new List<OpenApiSecurityRequirement> { new() { [new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }] = Array.Empty<string>() } }; }
return Task.CompletedTask; }); }); }
builder.Services.ConfigureHttpClientDefaults(http => { // Turn on resilience by default http.AddStandardResilienceHandler();
// Turn on service discovery by default http.AddServiceDiscovery(); });
builder.Services.Configure<ServiceDiscoveryOptions>(options => options.AllowedSchemes = ["https"]);
return builder; }
public static TBuilder ConfigureOpenTelemetry<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder { builder.Logging.AddOpenTelemetry(logging => { logging.IncludeFormattedMessage = true; logging.IncludeScopes = true; });
builder.Services.AddOpenTelemetry() .WithMetrics(metrics => metrics.AddAspNetCoreInstrumentation() .AddHttpClientInstrumentation() .AddRuntimeInstrumentation() ) .WithTracing(tracing => tracing.AddSource(builder.Environment.ApplicationName) .AddAspNetCoreInstrumentation(tracing => // Exclude health check requests from tracing tracing.Filter = context => !context.Request.Path.StartsWithSegments(HealthEndpointPath) && !context.Request.Path.StartsWithSegments(AlivenessEndpointPath) ) // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package) //.AddGrpcClientInstrumentation() .AddHttpClientInstrumentation() );
builder.AddOpenTelemetryExporters();
return builder; }
private static TBuilder AddOpenTelemetryExporters<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder { var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);
if (useOtlpExporter) { builder.Services.AddOpenTelemetry().UseOtlpExporter(); }
return builder; }
public static TBuilder AddDefaultHealthChecks<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder { builder.Services.AddHealthChecks() // Add a default liveness check to ensure app is responsive .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);
return builder; }
public static WebApplication MapDefaultEndpoints(this WebApplication app) { // Adding health checks endpoints to applications in non-development environments has security implications. // See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments. if (app.Environment.IsDevelopment()) { app.MapOpenApi();
// All health checks must pass for app to be considered ready to accept traffic after starting app.MapHealthChecks(HealthEndpointPath);
// Only health checks tagged with the "live" tag must pass for app to be considered alive app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions { Predicate = r => r.Tags.Contains("live") }); }
return app; }}