TestPublish.Add
1.0.1
dotnet add package TestPublish.Add --version 1.0.1
NuGet\Install-Package TestPublish.Add -Version 1.0.1
<PackageReference Include="TestPublish.Add" Version="1.0.1" />
<PackageVersion Include="TestPublish.Add" Version="1.0.1" />
<PackageReference Include="TestPublish.Add" />
paket add TestPublish.Add --version 1.0.1
#r "nuget: TestPublish.Add, 1.0.1"
#:package TestPublish.Add@1.0.1
#addin nuget:?package=TestPublish.Add&version=1.0.1
#tool nuget:?package=TestPublish.Add&version=1.0.1
Gateway Project
Overview
The Gateway project is designed to act as an API Gateway for various microservices. It leverages Ocelot for routing, caching, and middleware, and includes a robust caching mechanism that supports both Redis and In-Memory caching.
Gateway.Infrastructure
The Gateway.Infrastructure project contains shared components and extensions used across the gateway and services. It includes:
Caching:
- Provides a unified interface (
ICacheService) for caching. - Supports both Redis and In-Memory caching.
- Configurable via the
appsettings.jsonfile.
- Provides a unified interface (
Extensions:
CachingExtension: Configures caching based on theCacheProvidersetting in the configuration.- Other extensions for logging, JWT authentication, and OpenTelemetry.
Middleware:
- Custom middleware for logging requests and responses.
Caching Configuration
The caching mechanism is configured in the appsettings.json file. You can choose between Redis and In-Memory caching by setting the CacheProvider key.
Example Configuration
{
"CacheProvider": "Redis",
"ConnectionStrings": {
"Redis": "localhost:6379"
}
}
How to Use Caching
The ICacheService interface provides methods to interact with the cache. The implementation (Redis or In-Memory) is selected based on the configuration.
Pseudo Code Example
public class ExampleService
{
private readonly ICacheService _cacheService;
public ExampleService(ICacheService cacheService)
{
_cacheService = cacheService;
}
public async Task<string> GetDataAsync(string key)
{
// Check if data exists in cache
var cachedData = await _cacheService.GetAsync<string>(key);
if (cachedData != null)
{
return cachedData;
}
// Fetch data from source (e.g., database)
var data = "Fetched Data";
// Store data in cache
await _cacheService.SetAsync(key, data, TimeSpan.FromMinutes(10));
return data;
}
}
Setting Up Redis with Docker Compose
To set up Redis for caching, use the provided docker-compose.yml file. This file defines the Redis service.
Steps to Run Redis
- Navigate to the directory containing the
docker-compose.ymlfile. - Run the following command in your terminal:
docker-compose up -d
Ocelot API Gateway
Ocelot is used as the API Gateway for routing requests to downstream services. It supports features like:
Routing:
- Routes are defined in the
ocelot.jsonfile. - Each route specifies the upstream path and the downstream service.
- Routes are defined in the
Caching:
- Ocelot supports request-level caching to improve performance.
Middleware:
- Custom middleware can be added to handle cross-cutting concerns like logging and authentication.
- Implementation:A custom middleware captures unhandled exceptions, logs them, and returns structured error responses.
Pseudo Code Example
public class ExceptionHandlingMiddleware
{
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
private readonly RequestDelegate _next;
public ExceptionHandlingMiddleware(ILogger<ExceptionHandlingMiddleware> logger, RequestDelegate next)
{
_logger = logger;
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (OperationCanceledException ocex) when (context.RequestAborted.IsCancellationRequested)
{
_logger.LogWarning(ocex, "Request was cancelled by the client.");
context.Response.Clear();
context.Response.StatusCode = 499;
await context.Response.WriteAsync(JsonSerializer.Serialize(new
{
StatusCode = 499,
Message = "The request was cancelled by the client."
}));
}
catch (Exception ex)
{
_logger.LogError(ex, "Unhandled exception occurred");
context.Response.Clear();
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var response = new
{
StatusCode = context.Response.StatusCode,
Message = "An unexpected error occurred. Please try again later.",
Detailed = ex.Message
};
await context.Response.WriteAsync(JsonSerializer.Serialize(response));
}
}
}
4.Request/Response Transformations: Ocelot supports transformations for modifying headers, body, or other properties in both requests and responses.
Use Case:
Adding custom headers for authentication.
Modifying responses before sending them to clients.
Example Configuration
{
"UpstreamHeaderTransform": {
"X-Client-Secret": "test-secret"
},
"DownstreamHeaderTransform": {
"X-Client-Secret": "test-secret"
}
}
5.Service Discovery: Service discovery allows Ocelot to dynamically route requests to services registered in Consul.
Example Ocelot Configuration
``csharp { "GlobalConfiguration": { "BaseUrl": "http://localhost:5000", "ServiceDiscoveryProvider": { "Host": "localhost", "Port": 8500, "Type": "Consul" } } }
## Backend Service Setup:
Each service must register itself in Consul.
Steps:
1.Configure Consul service address.
2.Register the service during startup.
### Code:
```csharp
// Register Consul in Program.cs
builder.Services.RegisterConsulAddress(builder.Configuration);
app.RegisterService(app.Configuration, app.Lifetime);
Example Service Metadata:
"ServiceConfig": {
"ID": "Auth-5100",
"Name": "AuthService",
"Address": "localhost",
"Port": 5100,
"Check": {
"HTTP": "http://host.docker.internal:5100/api/HealthCheck/health-check",
"Interval": "10s",
"Timeout": "5s",
"DeregisterCriticalServiceAfter": "2m"
}
}
Verification:
-View all services: http://localhost:8500/ui -View metadata of AuthService: http://localhost:8500/v1/catalog/service/AuthService
Example Ocelot Configuration
{
"Routes": [
{
"DownstreamPathTemplate": "/api/articles",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/article-api",
"UpstreamHttpMethod": [ "GET" ]
}
]
}
Summary
The Gateway project provides a scalable and configurable API Gateway solution. With its caching capabilities, exception handling, request/response transformations, and service discovery via Consul, it ensures high performance, resilience, and flexibility for microservices architectures.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.