Part 1️⃣ - Common Shared Library |๐ Build .NET 8 eCommerce Microservice ๐with API Gateway, Rate Limiting, Caching & more ๐งบ
RESPONSE
This code defines a C# record named Response
with two properties: Flag
, a boolean initialized to false
, and Message
, a string that defaults to null
. Records in C# are immutable reference types that provide built-in functionality for value equality and concise syntax for defining data containers.
GLOBAL EXCEPTION
This code defines a middleware class named GlobalException
for handling exceptions and specific HTTP response statuses in an ASP.NET Core application. The middleware checks for and modifies responses with status codes 401 (Unauthorized), 403 (Forbidden), and 429 (Too Many Requests). It also handles internal server errors and request timeouts by logging the exceptions and sending user-friendly error messages in JSON format.
Key components of this middleware include:
- Dependencies: Uses
Microsoft.AspNetCore.Http
,Microsoft.AspNetCore.Mvc
,System.Net
, andSystem.Text.Json
. - Constructor: Takes a
RequestDelegate
callednext
. - InvokeAsync: The main method that processes HTTP requests, handles exceptions, and modifies response headers based on specific conditions.
- ModifyHeader: A private method that sets the response content type to JSON and writes a user-friendly error message to the response.
Functionality:
- Constructor: Stores the
RequestDelegate
for the next middleware in the pipeline. - InvokeAsync:
- Tries to process the request by calling the next middleware.
- Modifies the response for specific status codes (401, 403, 429).
- Catches exceptions, logs them, and modifies the response for internal server errors and request timeouts.
- ModifyHeader:
- Sets the response content type to JSON.
- Writes a
ProblemDetails
object with the error message, status code, and title to the response.
This middleware ensures that user-friendly messages are sent to the client for specific error conditions, enhancing the user experience by providing clear and concise error information.
List To Only Gateway API
This code defines a middleware class named ListenToOnlyApiGateway
that ensures requests are processed only if they originate from an API Gateway. It does this by checking for a specific header (Api-Gateway
) in the request. If the header is not present, the middleware responds with a 503 Service Unavailable status and a relevant message.
Key components of this middleware include:
- Dependencies: Uses
Microsoft.AspNetCore.Http
. - Constructor: Takes a
RequestDelegate
callednext
. - InvokeAsync: The main method that processes HTTP requests, checks for the
Api-Gateway
header, and either forwards the request to the next middleware or returns a 503 status code.
Functionality:
- Constructor: Stores the
RequestDelegate
for the next middleware in the pipeline. - InvokeAsync:
- Extracts the
Api-Gateway
header from the request. - Checks if the header is present:
- If the header is missing, sets the response status to 503 Service Unavailable and writes a message to the response body.
- If the header is present, forwards the request to the next middleware.
- Extracts the
GENERIC INTERFACE
This code defines a generic interface IGenericInterface<T>
in C# for basic CRUD operations and querying entities. The interface provides a standard set of methods for creating, updating, deleting, and retrieving entities, making it reusable for different types of entities in an application. The operations return a custom Response
type for indicating the result of the operation.
Key components of this interface include:
- Dependencies: Uses
eCommerce.SharedLibrary.Responses
andSystem.Linq.Expressions
. - Generic Type Parameter:
T
is constrained to be a class. - CRUD Methods: Defines methods for Create, Update, Delete, and Retrieve operations.
This interface provides a consistent way to handle data operations across different entity types, promoting code reuse and maintainability. The use of generic type parameter T
allows it to be flexible and applicable to various entities within the application.
JWT AUTHENTICATION SCHEME
This code defines a static class JWTAuthenticationScheme
that provides an extension method to add and configure JWT (JSON Web Token) authentication in an ASP.NET Core application. This extension method is designed to be used with the dependency injection system, allowing easy integration of JWT authentication.
Key components of this implementation include:
- Dependencies: Uses
Microsoft.AspNetCore.Authentication.JwtBearer
,Microsoft.Extensions.Configuration
,Microsoft.Extensions.DependencyInjection
, andMicrosoft.IdentityModel.Tokens
. - Extension Method: The
AddJWTAuthenticationScheme
method configures the JWT authentication scheme using settings from the application's configuration.
Functionality:
- Extension Method:
- Configures JWT authentication using settings from the application's configuration file (public static IServiceCollection AddJWTAuthenticationScheme(this IServiceCollection services, IConfiguration config)
appsettings.json
or another configuration source). - Adds the JWT authentication scheme to the service collection. - Configures theJwtBearer
options: - Retrieves the key, issuer, and audience from the configuration. - SetsRequireHttpsMetadata
to false to allow HTTP (not recommended for production). - Saves the token after successful authentication. - Sets up token validation parameters, including validation of the issuer, audience, and signing key using a symmetric security key.
This extension method simplifies the setup of JWT authentication in an ASP.NET Core application, ensuring that the necessary configuration is added to the dependency injection container. By calling AddJWTAuthenticationScheme
in the Startup.cs
or Program.cs
file, developers can easily integrate JWT authentication into their application.
SHARED SERVICE CONTAINER
This code defines a static class SharedServiceContainer
that provides extension methods to add and configure shared services and middleware in an ASP.NET Core application. These methods include setting up a database context, configuring logging with Serilog, adding JWT authentication, and registering custom middleware.
# Here's a follow-up section to encourage engagement and support for Netcode-Hub:
๐ Get in touch with Netcode-Hub! ๐ซ
1. GitHub: [Explore Repositories] ๐
2. Twitter: [Stay Updated] ๐ฆ
3. Facebook: [Connect Here]๐
4. LinkedIn: [Professional Network]๐
5. Email: [business.netcodehub@gmail.com] ๐ง
# ☕️ If you've found value in Netcode-Hub's work, consider supporting the channel with a coffee!
Comments
Post a Comment