Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/CSharpApp.Api/CSharpApp.Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

<ItemGroup>
<ProjectReference Include="..\CSharpApp.Core\CSharpApp.Core.csproj" />
<ProjectReference Include="..\CSharpApp.Models\CSharpApp.Models.csproj" />
<ProjectReference Include="..\CSharpApp.Infrastructure\CSharpApp.Infrastructure.csproj" />
</ItemGroup>

Expand Down
5 changes: 4 additions & 1 deletion src/CSharpApp.Api/GlobalUsings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@

global using CSharpApp.Core.Interfaces;
global using CSharpApp.Infrastructure.Configuration;
global using Serilog;
global using Serilog;
// DTOs are provided by CSharpApp.Dtos but keep namespace CSharpApp.Core.Dtos for compatibility
global using CSharpApp.Core.Dtos;
global using Microsoft.AspNetCore.Http;
56 changes: 56 additions & 0 deletions src/CSharpApp.Api/Middleware/PerformanceLoggingMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using System.Diagnostics;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using CSharpApp.Core.Settings;

namespace CSharpApp.Api.Middleware;

public class PerformanceLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<PerformanceLoggingMiddleware> _logger;
private readonly PerformanceSettings _settings;

public PerformanceLoggingMiddleware(RequestDelegate next, ILogger<PerformanceLoggingMiddleware> logger, IOptions<PerformanceSettings> options)
{
_next = next;
_logger = logger;
_settings = options.Value;
}

public async Task InvokeAsync(HttpContext context)
{
var path = context.Request.Path.Value ?? string.Empty;
if (_settings.ExcludePaths.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
{
await _next(context);
return;
}

var sw = Stopwatch.StartNew();
var traceId = Activity.Current?.Id ?? context.TraceIdentifier;

try
{
await _next(context);
sw.Stop();

var status = context.Response?.StatusCode ?? 0;
var ms = sw.ElapsedMilliseconds;
if (ms >= _settings.WarningThresholdMs)
{
_logger.LogWarning("SLOW REQUEST {Method} {Path} responded {StatusCode} in {Duration}ms | TraceId={TraceId}", context.Request.Method, path, status, ms, traceId);
}
else
{
_logger.LogInformation("HTTP {Method} {Path} responded {StatusCode} in {Duration}ms | TraceId={TraceId}", context.Request.Method, path, status, ms, traceId);
}
}
catch (Exception ex)
{
sw.Stop();
_logger.LogError(ex, "ERROR REQUEST {Method} {Path} in {Duration}ms | TraceId={TraceId}", context.Request.Method, path, sw.ElapsedMilliseconds, traceId);
throw;
}
}
}
101 changes: 96 additions & 5 deletions src/CSharpApp.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
using CSharpApp.Core.Dtos;
using CSharpApp.Application;
using CSharpApp.Infrastructure;
using CSharpApp.Api;
using CSharpApp.Api.Validation;

var builder = WebApplication.CreateBuilder(args);

var logger = new LoggerConfiguration().ReadFrom.Configuration(builder.Configuration).CreateLogger();
Expand All @@ -6,11 +12,16 @@
// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
builder.Services.AddDefaultConfiguration();
builder.Services.AddHttpConfiguration();
builder.Services.AddDefaultConfiguration(builder.Configuration);
builder.Services.AddHttpConfiguration(builder.Configuration);
builder.Services.AddProblemDetails();
builder.Services.AddApiVersioning();

// Register application and infrastructure services via extension helpers
builder.Services.AddApiServices();
builder.Services.AddApplicationServices();
builder.Services.AddInfrastructureServices(builder.Configuration);

var app = builder.Build();

// Configure the HTTP request pipeline.
Expand All @@ -21,14 +32,94 @@

//app.UseHttpsRedirection();

// Performance logging middleware
app.UseMiddleware<CSharpApp.Api.Middleware.PerformanceLoggingMiddleware>();

var versionedEndpointRouteBuilder = app.NewVersionedApi();

versionedEndpointRouteBuilder.MapGet("api/v{version:apiVersion}/getproducts", async (IProductsService productsService) =>
versionedEndpointRouteBuilder.MapGet("api/v{version:apiVersion}/products", async (IProductsService productsService, int? offset, int? limit) =>
{
var products = await productsService.GetProducts();
return products;
var products = await productsService.GetProducts(offset, limit);
return Results.Ok(products);
})
.WithName("GetProducts")
.HasApiVersion(1.0);

versionedEndpointRouteBuilder.MapGet("api/v{version:apiVersion}/products/{id}", async (IProductsService productsService, int id, CancellationToken ct) =>
{
var product = await productsService.GetProductById(id, ct);
return product is null ? Results.NotFound() : Results.Ok(product);
})
.WithName("GetProductById")
.HasApiVersion(1.0);

versionedEndpointRouteBuilder.MapPost("api/v{version:apiVersion}/products", async (IProductsService productsService, CSharpApp.Api.Validation.ICreateProductValidator apiValidator, CSharpApp.Application.Products.IProductValidator validator, CSharpApp.Application.Products.IProductMapper mapper, CreateProductRequestDto request, HttpContext http, CancellationToken ct) =>
{
if (request == null)
return Results.BadRequest();

// API-level validation (shape/format)
if (!apiValidator.Validate(request, out var apiErrors))
return Results.BadRequest(new { errors = apiErrors });

// Application/business validation
var validation = validator.ValidateForCreate(request);
if (!validation.IsValid)
return Results.BadRequest(new { errors = validation.Errors });

// Map request to domain product using mapper
var product = mapper.MapFromCreateRequest(request);

var created = await productsService.CreateProduct(product, ct);
if (created == null)
return Results.StatusCode(StatusCodes.Status502BadGateway);

var location = $"/api/v1/products/{created.Id}";
return Results.Created(location, created);
})
.WithName("CreateProduct")
.HasApiVersion(1.0);

versionedEndpointRouteBuilder.MapGet("api/v{version:apiVersion}/categories", async (ICategoriesService categoriesService) =>
{
var categories = await categoriesService.GetCategories();
return Results.Ok(categories);
})
.WithName("GetCategories")
.HasApiVersion(1.0);

versionedEndpointRouteBuilder.MapGet("api/v{version:apiVersion}/categories/{id}", async (ICategoriesService categoriesService, int id, CancellationToken ct) =>
{
var category = await categoriesService.GetCategoryById(id, ct);
return category is null ? Results.NotFound() : Results.Ok(category);
})
.WithName("GetCategoryById")
.HasApiVersion(1.0);

versionedEndpointRouteBuilder.MapPost("api/v{version:apiVersion}/categories", async (ICategoriesService categoriesService, CSharpApp.Api.Validation.ICreateCategoryValidator apiCategoryValidator, CSharpApp.Application.Categories.Validation.ICategoryValidator categoryValidator, CSharpApp.Application.Categories.Mapping.ICategoryMapper mapper, CSharpApp.Core.Dtos.CreateCategoryRequestDto request, CancellationToken ct) =>
{
if (request == null)
return Results.BadRequest();

// API-level validation
if (!apiCategoryValidator.Validate(request, out var apiErrors))
return Results.BadRequest(new { errors = apiErrors });

// Business validation
var businessValidation = categoryValidator.ValidateForCreate(request);
if (!businessValidation.IsValid)
return Results.BadRequest(new { errors = businessValidation.Errors });

var category = mapper.MapFromCreateRequest(request);

var created = await categoriesService.CreateCategory(category, ct);
if (created == null)
return Results.StatusCode(StatusCodes.Status502BadGateway);

var location = $"/api/v1/categories/{created.Id}";
return Results.Created(location, created);
})
.WithName("CreateCategory")
.HasApiVersion(1.0);

app.Run();
16 changes: 16 additions & 0 deletions src/CSharpApp.Api/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using Microsoft.Extensions.DependencyInjection;

namespace CSharpApp.Api
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddApiServices(this IServiceCollection services)
{
// API-level validators and request/adapters
services.AddSingleton<Validation.ICreateProductValidator, Validation.CreateProductValidator>();
services.AddSingleton<Validation.ICreateCategoryValidator, Validation.CreateCategoryValidator>();

return services;
}
}
}
26 changes: 26 additions & 0 deletions src/CSharpApp.Api/Validation/CreateCategoryValidator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
namespace CSharpApp.Api.Validation;

using CSharpApp.Core.Dtos;

public interface ICreateCategoryValidator
{
bool Validate(CreateCategoryRequestDto request, out System.Collections.Generic.List<string> errors);
}

public class CreateCategoryValidator : ICreateCategoryValidator
{
public bool Validate(CreateCategoryRequestDto request, out System.Collections.Generic.List<string> errors)
{
errors = new System.Collections.Generic.List<string>();
if (request == null)
{
errors.Add("Request cannot be null.");
return false;
}

if (string.IsNullOrWhiteSpace(request.Name))
errors.Add("Name is required.");

return errors.Count == 0;
}
}
32 changes: 32 additions & 0 deletions src/CSharpApp.Api/Validation/CreateProductValidator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
namespace CSharpApp.Api.Validation;

using CSharpApp.Core.Dtos;

public interface ICreateProductValidator
{
bool Validate(CreateProductRequestDto request, out System.Collections.Generic.List<string> errors);
}

public class CreateProductValidator : ICreateProductValidator
{
public bool Validate(CreateProductRequestDto request, out System.Collections.Generic.List<string> errors)
{
errors = new System.Collections.Generic.List<string>();
if (request == null)
{
errors.Add("Request cannot be null.");
return false;
}

if (string.IsNullOrWhiteSpace(request.Title))
errors.Add("Title is required.");

if (request.Price.HasValue && request.Price <= 0)
errors.Add("Price must be greater than zero when provided.");

if (request.CategoryId.HasValue && request.CategoryId <= 0)
errors.Add("CategoryId, when provided, must be a positive integer.");

return errors.Count == 0;
}
}
1 change: 1 addition & 0 deletions src/CSharpApp.Application/CSharpApp.Application.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

<ItemGroup>
<ProjectReference Include="..\CSharpApp.Core\CSharpApp.Core.csproj" />
<ProjectReference Include="..\CSharpApp.Models\CSharpApp.Models.csproj" />
</ItemGroup>

</Project>
99 changes: 99 additions & 0 deletions src/CSharpApp.Application/Categories/CategoriesService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
namespace CSharpApp.Application.Categories;

public class CategoriesService : ICategoriesService
{
private readonly HttpClient _httpClient;
private readonly RestApiSettings _restApiSettings;
private readonly ILogger<CategoriesService> _logger;

public CategoriesService(HttpClient httpClient, IOptions<RestApiSettings> restApiSettings,
ILogger<CategoriesService> logger)
{
_httpClient = httpClient;
_restApiSettings = restApiSettings.Value;
_logger = logger;
}

public async Task<IReadOnlyCollection<Category>> GetCategories(CancellationToken cancellationToken = default)
{
try
{
var path = string.IsNullOrWhiteSpace(_restApiSettings.Categories) ? string.Empty : _restApiSettings.Categories;

var response = await _httpClient.GetAsync(path, cancellationToken);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync(cancellationToken);

var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var res = JsonSerializer.Deserialize<List<Category>>(content, options) ?? new List<Category>();

return res.AsReadOnly();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error fetching categories from remote API");
throw;
}
}

public async Task<Category?> GetCategoryById(int id, CancellationToken cancellationToken = default)
{
try
{
var path = string.IsNullOrWhiteSpace(_restApiSettings.Categories) ? $"{id}" : $"{_restApiSettings.Categories}/{id}";

var response = await _httpClient.GetAsync(path, cancellationToken);

if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}

response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync(cancellationToken);

var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var category = JsonSerializer.Deserialize<Category>(content, options);

return category;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error fetching category {CategoryId} from remote API", id);
throw;
}
}

public async Task<Category?> CreateCategory(Category category, CancellationToken cancellationToken = default)
{
try
{
if (category is null)
throw new ArgumentNullException(nameof(category));

var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var json = JsonSerializer.Serialize(category, options);
using var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

var path = string.IsNullOrWhiteSpace(_restApiSettings.Categories) ? string.Empty : _restApiSettings.Categories;

var response = await _httpClient.PostAsync(path, content, cancellationToken);

if (!response.IsSuccessStatusCode)
{
_logger.LogWarning("Failed to create category. StatusCode: {StatusCode}", response.StatusCode);
return null;
}

var responseContent = await response.Content.ReadAsStringAsync(cancellationToken);
var created = JsonSerializer.Deserialize<Category>(responseContent, options);

return created ?? category;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error creating category");
throw;
}
}
}
Loading