2
0
Files
dotnet-interview-exercise/service/Program.cs

65 lines
2.3 KiB
C#

using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Polly.Simmy;
using service;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var services = builder.Services;
services.AddRequestTimeouts();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
services.AddEndpointsApiExplorer();
services.AddSwaggerGen();
services.AddDbContext<AppDbContext>(optionsBuilder =>
{
// Configure the database connection string.
var connectionString = builder.Configuration.GetValue<string>("PostgresConnection");
Console.WriteLine($"Connecting to PostgreSQL database with connection string: {connectionString}");
optionsBuilder.UseNpgsql(connectionString);
});
var httpClientBuilder = services.AddHttpClient<JsonPlaceholderClient>();
#region Exercise Phase 4
httpClientBuilder.AddResilienceHandler("chaos", configure =>
{
// Simulate network chaos by adding latency and random errors.
configure
.AddChaosLatency(0.10, TimeSpan.FromSeconds(3))
.AddChaosOutcome(0.15, () => new HttpResponseMessage(System.Net.HttpStatusCode.BadGateway))
.AddChaosOutcome(0.20, () => new HttpResponseMessage(System.Net.HttpStatusCode.ServiceUnavailable))
.AddChaosOutcome(0.10, () =>
{
Thread.Sleep(TimeSpan.FromSeconds(2)); // Delay the error response, as it would likely happen with a 504.
return new HttpResponseMessage(System.Net.HttpStatusCode.GatewayTimeout);
});
});
#endregion
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI(); // Swagger UI is available at http://localhost:8080/swagger/index.html
app.UseRequestTimeouts();
app.MapGet("/posts/{id}", async (AppDbContext dbContext, JsonPlaceholderClient client, int id) =>
{
// TODO: (Phase 1) Implement the logic to retrieve a post by ID and store it in the database.
// Consider some minimal error handling in case the post is not found (e.g. Id > 100).
return Results.Ok();
})
.WithRequestTimeout(TimeSpan.FromSeconds(29))
.WithName("GetPostById")
.WithOpenApi();
app.Run();