TestPublish.Add 1.0.1

dotnet add package TestPublish.Add --version 1.0.1
                    
NuGet\Install-Package TestPublish.Add -Version 1.0.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="TestPublish.Add" Version="1.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="TestPublish.Add" Version="1.0.1" />
                    
Directory.Packages.props
<PackageReference Include="TestPublish.Add" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add TestPublish.Add --version 1.0.1
                    
#r "nuget: TestPublish.Add, 1.0.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package TestPublish.Add@1.0.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=TestPublish.Add&version=1.0.1
                    
Install as a Cake Addin
#tool nuget:?package=TestPublish.Add&version=1.0.1
                    
Install as a Cake Tool

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:

  1. Caching:

    • Provides a unified interface (ICacheService) for caching.
    • Supports both Redis and In-Memory caching.
    • Configurable via the appsettings.json file.
  2. Extensions:

    • CachingExtension: Configures caching based on the CacheProvider setting in the configuration.
    • Other extensions for logging, JWT authentication, and OpenTelemetry.
  3. 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

  1. Navigate to the directory containing the docker-compose.yml file.
  2. 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:

  1. Routing:

    • Routes are defined in the ocelot.json file.
    • Each route specifies the upstream path and the downstream service.
  2. Caching:

    • Ocelot supports request-level caching to improve performance.
  3. 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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • 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.

Version Downloads Last Updated
1.0.1 194 10/21/2025
1.0.0 197 10/21/2025