Presence.Desktop/presence_api/Program.cs
2024-12-20 11:49:17 +03:00

114 lines
3.3 KiB
C#

using data.Domain.UseCase;
using data.RemoteData.RemoteDataBase;
using data.Repository;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
var builder = WebApplication.CreateBuilder(args);
// Äîáàâëåíèå êîíòåêñòà áàçû äàííûõ è ðåïîçèòîðèåâ
builder.Services.AddDbContext<RemoteDatabaseContext>();
// Ðåãèñòðèðóåì ðåïîçèòîðèè è UseCase
builder.Services.AddScoped<IUserRepository, SQLUserRepositoryImpl>()
.AddScoped<IPresenceRepository, SQLPresenceRepositoryImpl>()
.AddScoped<IGroupRepository, SQLGroupRepositoryImpl>()
.AddScoped<UseCaseGeneratePresence>()
.AddScoped<GroupUseCase>();
// Äîáàâëåíèå êîíòðîëëåðîâ
builder.Services.AddControllers();
// Äîáàâëåíèå Swagger äëÿ API äîêóìåíòàöèè
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Äîáàâëÿåì ëîãèðîâàíèå
builder.Services.AddLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole(options =>
{
options.LogToStandardErrorThreshold = LogLevel.Error;
});
logging.AddDebug();
logging.SetMinimumLevel(LogLevel.Error);
});
var app = builder.Build();
// Êîíôèãóðàöèÿ Swagger UI äëÿ ðàçðàáîòêè
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
// Äîáàâëÿåì middleware äëÿ ëîãèðîâàíèÿ ëþáûõ îøèáîê
app.UseMiddleware<ErrorLoggingMiddleware>();
// Îñíîâíûå Middleware
app.UseHttpsRedirection();
app.MapControllers();
app.Run();
public class ErrorLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ErrorLoggingMiddleware> _logger;
public ErrorLoggingMiddleware(RequestDelegate next, ILogger<ErrorLoggingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
// Ïåðåäà÷à çàïðîñà äàëüøå ïî êîíâåéåðó
await _next(context);
// Ïðîâåðÿåì êîäû ñîñòîÿíèÿ è ëîãèðóåì îøèáêè 4xx è 5xx
if (context.Response.StatusCode >= 400)
{
var logLevel = context.Response.StatusCode >= 500 ? LogLevel.Error : LogLevel.Warning;
_logger.Log(logLevel, "Îòâåò ñ îøèáêîé: {StatusCode} äëÿ {Method} {Path}",
context.Response.StatusCode, context.Request.Method, context.Request.Path);
}
}
catch (Exception ex)
{
// Ëîãèðóåì íåîáðàáîòàííîå èñêëþ÷åíèå
_logger.LogError(ex, "Íåîáðàáîòàííîå èñêëþ÷åíèå â çàïðîñå {Method} {Path}: {Message}",
context.Request.Method, context.Request.Path, ex.Message);
// Óñòàíàâëèâàåì ñòàòóñ îòâåòà
context.Response.StatusCode = 500;
await context.Response.WriteAsync("Ïðîèçîøëà âíóòðåííÿÿ îøèáêà ñåðâåðà.");
}
}
}
// Ïðèìåð êîíòðîëëåðà äëÿ ïðîâåðêè âñåõ îøèáîê
[ApiController]
[Route("api/[controller]")]
public class TestController : ControllerBase
{
[HttpGet("bad-request")]
public IActionResult BadRequestExample()
{
return BadRequest("Ýòî ïðèìåð îøèáêè 400.");
}
[HttpGet("internal-error")]
public IActionResult InternalServerErrorExample()
{
throw new InvalidOperationException("Ýòî ïðèìåð íåîáðàáîòàííîé îøèáêè.");
}
}