diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor
index 661f118..39eae8e 100644
--- a/Client.Wasm/Components/StudentCard.razor
+++ b/Client.Wasm/Components/StudentCard.razor
@@ -4,10 +4,10 @@
- Номер №X "Название лабораторной"
- Вариант №Х "Название варианта"
- Выполнена Фамилией Именем 65ХХ
- Ссылка на форк
+ Номер №1 "Кэширование"
+ Вариант №53 "Кредитная заявка"
+ Выполнена Уваровым Никитой 6513
+ Ссылка на форк
diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json
index d1fe7ab..fde6270 100644
--- a/Client.Wasm/wwwroot/appsettings.json
+++ b/Client.Wasm/wwwroot/appsettings.json
@@ -6,5 +6,5 @@
}
},
"AllowedHosts": "*",
- "BaseAddress": ""
+ "BaseAddress": "https://localhost:7184/api/Credit/"
}
diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln
index cb48241..02142d4 100644
--- a/CloudDevelopment.sln
+++ b/CloudDevelopment.sln
@@ -1,10 +1,18 @@
Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio Version 17
-VisualStudioVersion = 17.14.36811.4
+# Visual Studio Version 18
+VisualStudioVersion = 18.3.11512.155 d18.3
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client.Wasm", "Client.Wasm\Client.Wasm.csproj", "{AE7EEA74-2FE0-136F-D797-854FD87E022A}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApp.AppHost", "CreditApp.AppHost\CreditApp.AppHost.csproj", "{5432516B-65B7-417A-9D7C-D87F95B880D5}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApp.ServiceDefaults", "CreditApp.ServiceDefaults\CreditApp.ServiceDefaults.csproj", "{2A1134C7-1080-475D-2A48-9F65479D8C91}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApp.Api", "CreditApp.Api\CreditApp.Api.csproj", "{E7D4CA8B-53EA-9676-D96D-BE2F0CB11054}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditApp.Domain", "CreditApp.Domain\CreditApp.Domain.csproj", "{B3DC2A03-88A2-468A-BE14-95A1F4DEA883}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -15,6 +23,22 @@ Global
{AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.Build.0 = Release|Any CPU
+ {5432516B-65B7-417A-9D7C-D87F95B880D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {5432516B-65B7-417A-9D7C-D87F95B880D5}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {5432516B-65B7-417A-9D7C-D87F95B880D5}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {5432516B-65B7-417A-9D7C-D87F95B880D5}.Release|Any CPU.Build.0 = Release|Any CPU
+ {2A1134C7-1080-475D-2A48-9F65479D8C91}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {2A1134C7-1080-475D-2A48-9F65479D8C91}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {2A1134C7-1080-475D-2A48-9F65479D8C91}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {2A1134C7-1080-475D-2A48-9F65479D8C91}.Release|Any CPU.Build.0 = Release|Any CPU
+ {E7D4CA8B-53EA-9676-D96D-BE2F0CB11054}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {E7D4CA8B-53EA-9676-D96D-BE2F0CB11054}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {E7D4CA8B-53EA-9676-D96D-BE2F0CB11054}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {E7D4CA8B-53EA-9676-D96D-BE2F0CB11054}.Release|Any CPU.Build.0 = Release|Any CPU
+ {B3DC2A03-88A2-468A-BE14-95A1F4DEA883}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {B3DC2A03-88A2-468A-BE14-95A1F4DEA883}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {B3DC2A03-88A2-468A-BE14-95A1F4DEA883}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {B3DC2A03-88A2-468A-BE14-95A1F4DEA883}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/CreditApp.Api/Controllers/CreditController.cs b/CreditApp.Api/Controllers/CreditController.cs
new file mode 100644
index 0000000..62bb91c
--- /dev/null
+++ b/CreditApp.Api/Controllers/CreditController.cs
@@ -0,0 +1,33 @@
+using CreditApp.Api.Services;
+using CreditApp.Domain.Data;
+using Microsoft.AspNetCore.Mvc;
+
+namespace CreditApp.Api.Controllers;
+
+[ApiController]
+[Route("api/[controller]")]
+public class CreditController(
+ ICreditService creditService,
+ ILogger logger)
+ : ControllerBase
+{
+ ///
+ /// Получить кредитную заявку по идентификатору
+ ///
+ [HttpGet]
+ [ProducesResponseType(typeof(CreditApplication), StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ public async Task> Get(
+ int id,
+ CancellationToken cancellationToken)
+ {
+ if (id <= 0)
+ return BadRequest("Id must be positive number");
+
+ logger.LogInformation("Request credit application {CreditId}", id);
+
+ var result = await creditService.GetAsync(id, cancellationToken);
+
+ return Ok(result);
+ }
+}
\ No newline at end of file
diff --git a/CreditApp.Api/CreditApp.Api.csproj b/CreditApp.Api/CreditApp.Api.csproj
new file mode 100644
index 0000000..e88d1af
--- /dev/null
+++ b/CreditApp.Api/CreditApp.Api.csproj
@@ -0,0 +1,21 @@
+
+
+
+ net8.0
+ enable
+ enable
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/CreditApp.Api/Program.cs b/CreditApp.Api/Program.cs
new file mode 100644
index 0000000..60bbc18
--- /dev/null
+++ b/CreditApp.Api/Program.cs
@@ -0,0 +1,39 @@
+using CreditApp.Api.Services;
+using CreditApp.ServiceDefaults;
+
+var builder = WebApplication.CreateBuilder(args);
+
+builder.AddServiceDefaults();
+builder.AddRedisDistributedCache("redis");
+
+builder.Services.AddControllers();
+builder.Services.AddEndpointsApiExplorer();
+builder.Services.AddSwaggerGen();
+
+builder.Services.AddCors(options =>
+{
+ options.AddPolicy("wasm", policy =>
+ {
+ policy.AllowAnyOrigin()
+ .WithMethods("GET")
+ .WithHeaders("Content-Type");
+ });
+});
+
+builder.Services.AddScoped();
+
+var app = builder.Build();
+
+if (app.Environment.IsDevelopment())
+{
+ app.UseSwagger();
+ app.UseSwaggerUI();
+}
+
+app.MapDefaultEndpoints();
+app.UseHttpsRedirection();
+app.UseCors("wasm");
+app.UseAuthorization();
+app.MapControllers();
+
+app.Run();
diff --git a/CreditApp.Api/Properties/launchSettings.json b/CreditApp.Api/Properties/launchSettings.json
new file mode 100644
index 0000000..e9e6313
--- /dev/null
+++ b/CreditApp.Api/Properties/launchSettings.json
@@ -0,0 +1,41 @@
+{
+ "$schema": "http://json.schemastore.org/launchsettings.json",
+ "iisSettings": {
+ "windowsAuthentication": false,
+ "anonymousAuthentication": true,
+ "iisExpress": {
+ "applicationUrl": "http://localhost:50546",
+ "sslPort": 44330
+ }
+ },
+ "profiles": {
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "launchUrl": "swagger",
+ "applicationUrl": "http://localhost:5144",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "launchUrl": "swagger",
+ "applicationUrl": "https://localhost:7184;http://localhost:5144",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "IIS Express": {
+ "commandName": "IISExpress",
+ "launchBrowser": true,
+ "launchUrl": "swagger",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ }
+ }
+}
diff --git a/CreditApp.Api/Services/CreditGenerator.cs b/CreditApp.Api/Services/CreditGenerator.cs
new file mode 100644
index 0000000..0232893
--- /dev/null
+++ b/CreditApp.Api/Services/CreditGenerator.cs
@@ -0,0 +1,62 @@
+using Bogus;
+using CreditApp.Domain.Data;
+
+namespace CreditApp.Api.Services;
+
+///
+/// Генератор тестовых данных для кредитных заявок.
+///
+public static class CreditGenerator
+{
+ private const double CbRate = 16.0;
+
+ private static readonly string[] _statuses =
+ {
+ "Новая",
+ "В обработке",
+ "Одобрена",
+ "Отклонена"
+ };
+
+ private static readonly string[] _types =
+ {
+ "Потребительский",
+ "Ипотека",
+ "Автокредит"
+ };
+
+ private static readonly Faker _faker =
+ new Faker()
+ .RuleFor(x => x.Id, f => f.IndexFaker)
+ .RuleFor(x => x.CreditType, f => f.PickRandom(_types))
+ .RuleFor(x => x.RequestedAmount,
+ f => Math.Round(f.Random.Decimal(10_000, 5_000_000), 2))
+ .RuleFor(x => x.TermMonths,
+ f => f.Random.Int(6, 360))
+ .RuleFor(x => x.InterestRate,
+ f => Math.Round(f.Random.Double(CbRate, CbRate + 5), 2))
+ .RuleFor(x => x.ApplicationDate,
+ f => DateOnly.FromDateTime(f.Date.Past(2)))
+ .RuleFor(x => x.HasInsurance,
+ f => f.Random.Bool())
+ .RuleFor(x => x.Status,
+ f => f.PickRandom(_statuses))
+ .RuleFor(x => x.DecisionDate, (f, x) =>
+ x.Status is "Одобрена" or "Отклонена"
+ ? DateOnly.FromDateTime(
+ f.Date.Between(
+ x.ApplicationDate.ToDateTime(TimeOnly.MinValue),
+ DateTime.Now))
+ : null)
+ .RuleFor(x => x.ApprovedAmount, (f, x) =>
+ x.Status == "Одобрена"
+ ? Math.Round(f.Random.Decimal(10_000, x.RequestedAmount), 2)
+ : null);
+
+ public static CreditApplication Generate(int id)
+ {
+ var result = _faker.Generate();
+ result.Id = id;
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/CreditApp.Api/Services/CreditService.cs b/CreditApp.Api/Services/CreditService.cs
new file mode 100644
index 0000000..b6f3ddc
--- /dev/null
+++ b/CreditApp.Api/Services/CreditService.cs
@@ -0,0 +1,58 @@
+using System.Text.Json;
+using CreditApp.Domain.Data;
+using Microsoft.Extensions.Caching.Distributed;
+
+namespace CreditApp.Api.Services;
+
+///
+/// Сервис для работы с кредитными заявками.
+///
+public class CreditService(
+ IDistributedCache cache,
+ ILogger logger)
+ : ICreditService
+{
+ private const string CachePrefix = "credit:";
+
+ public async Task GetAsync(
+ int id,
+ CancellationToken cancellationToken = default)
+ {
+ var key = $"{CachePrefix}{id}";
+
+ var cached = await cache.GetStringAsync(key, cancellationToken);
+
+ if (cached is not null)
+ {
+ logger.LogInformation(
+ "Cache HIT for credit application {CreditId}",
+ id);
+
+ return JsonSerializer.Deserialize(cached)!;
+ }
+
+ logger.LogInformation(
+ "Cache MISS for credit application {CreditId}",
+ id);
+
+ var result = CreditGenerator.Generate(id);
+
+ var serialized = JsonSerializer.Serialize(result);
+
+ var options = new DistributedCacheEntryOptions
+ {
+ AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
+ };
+
+ await cache.SetStringAsync(key, serialized, options, cancellationToken);
+
+ logger.LogInformation(
+ "Generated credit application {CreditId}. Type: {Type}, Amount: {Amount}, Status: {Status}",
+ result.Id,
+ result.CreditType,
+ result.RequestedAmount,
+ result.Status);
+
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/CreditApp.Api/Services/ICreditService.cs b/CreditApp.Api/Services/ICreditService.cs
new file mode 100644
index 0000000..06f478d
--- /dev/null
+++ b/CreditApp.Api/Services/ICreditService.cs
@@ -0,0 +1,13 @@
+using CreditApp.Domain.Data;
+
+namespace CreditApp.Api.Services;
+
+public interface ICreditService
+{
+ ///
+ /// Получить кредитную заявку по идентификатору
+ ///
+ public Task GetAsync(
+ int id,
+ CancellationToken cancellationToken = default);
+}
\ No newline at end of file
diff --git a/CreditApp.Api/appsettings.Development.json b/CreditApp.Api/appsettings.Development.json
new file mode 100644
index 0000000..0c208ae
--- /dev/null
+++ b/CreditApp.Api/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/CreditApp.Api/appsettings.json b/CreditApp.Api/appsettings.json
new file mode 100644
index 0000000..10f68b8
--- /dev/null
+++ b/CreditApp.Api/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "AllowedHosts": "*"
+}
diff --git a/CreditApp.AppHost/AppHost.cs b/CreditApp.AppHost/AppHost.cs
new file mode 100644
index 0000000..bc58dc4
--- /dev/null
+++ b/CreditApp.AppHost/AppHost.cs
@@ -0,0 +1,17 @@
+using Google.Protobuf.WellKnownTypes;
+
+var builder = DistributedApplication.CreateBuilder(args);
+
+var redis = builder.AddRedis("redis")
+ .WithRedisCommander();
+
+var api = builder.AddProject("api")
+ .WithReference(redis)
+ .WaitFor(redis);
+
+builder.AddProject("client")
+ .WithReference(api)
+ .WaitFor(api);
+
+builder.Build().Run();
+
diff --git a/CreditApp.AppHost/CreditApp.AppHost.csproj b/CreditApp.AppHost/CreditApp.AppHost.csproj
new file mode 100644
index 0000000..12f6ffc
--- /dev/null
+++ b/CreditApp.AppHost/CreditApp.AppHost.csproj
@@ -0,0 +1,21 @@
+
+
+
+ Exe
+ net8.0
+ enable
+ enable
+ b2dc854c-a0d1-4a18-8fc3-d0168e660b49
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/CreditApp.AppHost/Properties/launchSettings.json b/CreditApp.AppHost/Properties/launchSettings.json
new file mode 100644
index 0000000..4af7734
--- /dev/null
+++ b/CreditApp.AppHost/Properties/launchSettings.json
@@ -0,0 +1,31 @@
+{
+ "$schema": "https://json.schemastore.org/launchsettings.json",
+ "profiles": {
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "https://localhost:17244;http://localhost:15135",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "DOTNET_ENVIRONMENT": "Development",
+ "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21273",
+ "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:23257",
+ "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22263"
+ }
+ },
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:15135",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "DOTNET_ENVIRONMENT": "Development",
+ "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19038",
+ "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18140",
+ "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20023"
+ }
+ }
+ }
+}
diff --git a/CreditApp.AppHost/appsettings.Development.json b/CreditApp.AppHost/appsettings.Development.json
new file mode 100644
index 0000000..0c208ae
--- /dev/null
+++ b/CreditApp.AppHost/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/CreditApp.AppHost/appsettings.json b/CreditApp.AppHost/appsettings.json
new file mode 100644
index 0000000..31c092a
--- /dev/null
+++ b/CreditApp.AppHost/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning",
+ "Aspire.Hosting.Dcp": "Warning"
+ }
+ }
+}
diff --git a/CreditApp.Domain/CreditApp.Domain.csproj b/CreditApp.Domain/CreditApp.Domain.csproj
new file mode 100644
index 0000000..e1b91f9
--- /dev/null
+++ b/CreditApp.Domain/CreditApp.Domain.csproj
@@ -0,0 +1,9 @@
+
+
+
+ net8.0
+ enable
+ enable
+
+
+
\ No newline at end of file
diff --git a/CreditApp.Domain/Data/CreditApplication.cs b/CreditApp.Domain/Data/CreditApplication.cs
new file mode 100644
index 0000000..bcffdea
--- /dev/null
+++ b/CreditApp.Domain/Data/CreditApplication.cs
@@ -0,0 +1,45 @@
+namespace CreditApp.Domain.Data;
+
+public class CreditApplication
+{
+ ///
+ /// Идентификатор в системе
+ ///
+ public int Id { get; set; }
+ ///
+ /// Тип кредита
+ ///
+ public string CreditType { get; set; } = default!;
+ ///
+ /// Запрашиваемая сумма
+ ///
+ public decimal RequestedAmount { get; set; }
+ ///
+ /// Срок в месяцах
+ ///
+ public int TermMonths { get; set; }
+ ///
+ /// Процентная ставка
+ ///
+ public double InterestRate { get; set; }
+ ///
+ /// Дата подачи
+ ///
+ public DateOnly ApplicationDate { get; set; }
+ ///
+ /// Необходимость страховки
+ ///
+ public bool HasInsurance { get; set; }
+ ///
+ /// Статус заявки
+ ///
+ public string Status { get; set; } = default!;
+ ///
+ /// Дата решения
+ ///
+ public DateOnly? DecisionDate { get; set; }
+ ///
+ /// Одобренная сумма
+ ///
+ public decimal? ApprovedAmount { get; set; }
+}
diff --git a/CreditApp.ServiceDefaults/CreditApp.ServiceDefaults.csproj b/CreditApp.ServiceDefaults/CreditApp.ServiceDefaults.csproj
new file mode 100644
index 0000000..8ad6726
--- /dev/null
+++ b/CreditApp.ServiceDefaults/CreditApp.ServiceDefaults.csproj
@@ -0,0 +1,22 @@
+
+
+
+ net8.0
+ enable
+ enable
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/CreditApp.ServiceDefaults/Extensions.cs b/CreditApp.ServiceDefaults/Extensions.cs
new file mode 100644
index 0000000..c572403
--- /dev/null
+++ b/CreditApp.ServiceDefaults/Extensions.cs
@@ -0,0 +1,128 @@
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Diagnostics.HealthChecks;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Diagnostics.HealthChecks;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.ServiceDiscovery;
+using OpenTelemetry;
+using OpenTelemetry.Metrics;
+using OpenTelemetry.Trace;
+
+namespace CreditApp.ServiceDefaults;
+
+// 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-defaults
+public static class Extensions
+{
+ private const string HealthEndpointPath = "/health";
+ private const string AlivenessEndpointPath = "/alive";
+
+ public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder
+ {
+ builder.ConfigureOpenTelemetry();
+
+ builder.AddDefaultHealthChecks();
+
+ builder.Services.AddServiceDiscovery();
+
+ builder.Services.ConfigureHttpClientDefaults(http =>
+ {
+ // Turn on resilience by default
+ http.AddStandardResilienceHandler();
+
+ // Turn on service discovery by default
+ http.AddServiceDiscovery();
+ });
+
+ // Uncomment the following to restrict the allowed schemes for service discovery.
+ // builder.Services.Configure(options =>
+ // {
+ // options.AllowedSchemes = ["https"];
+ // });
+
+ return builder;
+ }
+
+ public static TBuilder ConfigureOpenTelemetry(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(this TBuilder builder) where TBuilder : IHostApplicationBuilder
+ {
+ var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);
+
+ if (useOtlpExporter)
+ {
+ builder.Services.AddOpenTelemetry().UseOtlpExporter();
+ }
+
+ // Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package)
+ //if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]))
+ //{
+ // builder.Services.AddOpenTelemetry()
+ // .UseAzureMonitor();
+ //}
+
+ return builder;
+ }
+
+ public static TBuilder AddDefaultHealthChecks(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())
+ {
+ // 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;
+ }
+}