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
4 changes: 3 additions & 1 deletion src/CSharpApp.Api/GlobalUsings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@

global using CSharpApp.Core.Interfaces;
global using CSharpApp.Infrastructure.Configuration;
global using Serilog;
global using Serilog;
global using CSharpApp.Core.Dtos;
global using Microsoft.AspNetCore.Http;
35 changes: 31 additions & 4 deletions src/CSharpApp.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
// 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();

Expand All @@ -23,12 +23,39 @@

var versionedEndpointRouteBuilder = app.NewVersionedApi();

versionedEndpointRouteBuilder.MapGet("api/v{version:apiVersion}/getproducts", async (IProductsService productsService) =>
versionedEndpointRouteBuilder.MapGet("api/v{version:apiVersion}/products", async (IProductsService productsService) =>
{
var products = await productsService.GetProducts();
return products;
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, Product product, HttpContext http, CancellationToken ct) =>
{
if (product == null)
return Results.BadRequest();

// Basic validation
if (string.IsNullOrWhiteSpace(product.Title) || (product.Price.HasValue && product.Price <= 0))
return Results.BadRequest("Invalid product payload");

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);

app.Run();
98 changes: 88 additions & 10 deletions src/CSharpApp.Application/Products/ProductsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,100 @@ public class ProductsService : IProductsService
private readonly RestApiSettings _restApiSettings;
private readonly ILogger<ProductsService> _logger;

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

public async Task<Product?> GetProductById(int id, CancellationToken cancellationToken = default)
{
try
{
var path = string.IsNullOrWhiteSpace(_restApiSettings.Products) ? $"{id}" : $"{_restApiSettings.Products}/{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 product = JsonSerializer.Deserialize<Product>(content, options);

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

public async Task<Product?> CreateProduct(Product product, CancellationToken cancellationToken = default)
{
try
{
// Basic validation
if (product is null)
throw new ArgumentNullException(nameof(product));

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

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

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

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

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

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

public async Task<IReadOnlyCollection<Product>> GetProducts()
{
_httpClient.BaseAddress = new Uri(_restApiSettings.BaseUrl!);
var response = await _httpClient.GetAsync(_restApiSettings.Products);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var res = JsonSerializer.Deserialize<List<Product>>(content);

return res.AsReadOnly();
try
{
// If Products path is set, request it; otherwise request root
var path = string.IsNullOrWhiteSpace(_restApiSettings.Products) ? string.Empty : _restApiSettings.Products;

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

var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};

var res = JsonSerializer.Deserialize<List<Product>>(content, options) ?? new List<Product>();

return res.AsReadOnly();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error fetching products from remote API");
throw;
}
}
}
}
2 changes: 2 additions & 0 deletions src/CSharpApp.Core/Interfaces/IProductsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@ namespace CSharpApp.Core.Interfaces;
public interface IProductsService
{
Task<IReadOnlyCollection<Product>> GetProducts();
Task<Product?> GetProductById(int id, CancellationToken cancellationToken = default);
Task<Product?> CreateProduct(Product product, CancellationToken cancellationToken = default);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,11 @@ namespace CSharpApp.Infrastructure.Configuration;

public static class DefaultConfiguration
{
public static IServiceCollection AddDefaultConfiguration(this IServiceCollection services)
public static IServiceCollection AddDefaultConfiguration(this IServiceCollection services, IConfiguration configuration)
{
var serviceProvider = services.BuildServiceProvider();
var configuration = serviceProvider.GetService<IConfiguration>();

services.Configure<RestApiSettings>(configuration!.GetSection(nameof(RestApiSettings)));
services.Configure<RestApiSettings>(configuration.GetSection(nameof(RestApiSettings)));
services.Configure<HttpClientSettings>(configuration.GetSection(nameof(HttpClientSettings)));

services.AddSingleton<IProductsService, ProductsService>();

return services;
}
}
}
24 changes: 22 additions & 2 deletions src/CSharpApp.Infrastructure/Configuration/HttpConfiguration.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,29 @@
using Microsoft.Extensions.Options;

namespace CSharpApp.Infrastructure.Configuration;

public static class HttpConfiguration
{
public static IServiceCollection AddHttpConfiguration(this IServiceCollection services)
public static IServiceCollection AddHttpConfiguration(this IServiceCollection services, IConfiguration configuration)
{
// Register a typed HttpClient for ProductsService using IHttpClientFactory
services.AddHttpClient<IProductsService, ProductsService>((sp, client) =>
{
var rest = sp.GetRequiredService<IOptions<RestApiSettings>>().Value;
var httpSettings = sp.GetRequiredService<IOptions<HttpClientSettings>>().Value;

if (!string.IsNullOrWhiteSpace(rest.BaseUrl))
{
client.BaseAddress = new Uri(rest.BaseUrl);
}

// Configure timeout from settings (LifeTime is seconds)
if (httpSettings.LifeTime > 0)
{
client.Timeout = TimeSpan.FromSeconds(httpSettings.LifeTime);
}
});

return services;
}
}
}
29 changes: 18 additions & 11 deletions src/CSharpApp.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
# Visual Studio Version 18
VisualStudioVersion = 18.6.11822.322 stable
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{09E4065D-8EA9-43F4-AB9C-5E70ACC35F88}"
EndProject
Expand All @@ -15,20 +15,13 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpApp.Core", "CSharpApp
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpApp.Infrastructure", "CSharpApp.Infrastructure\CSharpApp.Infrastructure.csproj", "{1D24449A-3896-48C5-B007-A33F8479456C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpApp.Tests", "test\CSharpApp.Tests\CSharpApp.Tests.csproj", "{FA0E527F-0190-B11D-0A5E-4007C794BEA2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{E3BB3FDA-5F80-48B0-B0A5-B29F89814132} = {09E4065D-8EA9-43F4-AB9C-5E70ACC35F88}
{5AEEC8AB-02B6-4051-A6EF-B785FC773E87} = {09E4065D-8EA9-43F4-AB9C-5E70ACC35F88}
{75D8AC89-79D6-4C05-88C5-E2BC6445F202} = {09E4065D-8EA9-43F4-AB9C-5E70ACC35F88}
{1D24449A-3896-48C5-B007-A33F8479456C} = {09E4065D-8EA9-43F4-AB9C-5E70ACC35F88}
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E3BB3FDA-5F80-48B0-B0A5-B29F89814132}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E3BB3FDA-5F80-48B0-B0A5-B29F89814132}.Debug|Any CPU.Build.0 = Debug|Any CPU
Expand All @@ -46,5 +39,19 @@ Global
{1D24449A-3896-48C5-B007-A33F8479456C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1D24449A-3896-48C5-B007-A33F8479456C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1D24449A-3896-48C5-B007-A33F8479456C}.Release|Any CPU.Build.0 = Release|Any CPU
{FA0E527F-0190-B11D-0A5E-4007C794BEA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FA0E527F-0190-B11D-0A5E-4007C794BEA2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FA0E527F-0190-B11D-0A5E-4007C794BEA2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FA0E527F-0190-B11D-0A5E-4007C794BEA2}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{E3BB3FDA-5F80-48B0-B0A5-B29F89814132} = {09E4065D-8EA9-43F4-AB9C-5E70ACC35F88}
{5AEEC8AB-02B6-4051-A6EF-B785FC773E87} = {09E4065D-8EA9-43F4-AB9C-5E70ACC35F88}
{75D8AC89-79D6-4C05-88C5-E2BC6445F202} = {09E4065D-8EA9-43F4-AB9C-5E70ACC35F88}
{1D24449A-3896-48C5-B007-A33F8479456C} = {09E4065D-8EA9-43F4-AB9C-5E70ACC35F88}
{FA0E527F-0190-B11D-0A5E-4007C794BEA2} = {AEEC3AD8-B5EE-4590-8714-024364B7557A}
EndGlobalSection
EndGlobal
26 changes: 26 additions & 0 deletions src/test/CSharpApp.Tests/CSharpApp.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="xunit" Version="2.5.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.7.0" />
</ItemGroup>

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

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.0" />
</ItemGroup>

</Project>
Loading