itenium-be / ASP.NET-WebApi

.NET Competence Center: WebApi course
2 stars 0 forks source link

Exercises on Middleware #1

Open Laoujin opened 5 months ago

Laoujin commented 5 months ago

Have a Controller Action method with:

--> Turn those three cross cutting concerns into 3 different middlewares

(if there isn't yet something like that...)

Others:

Laoujin commented 1 month ago

Retry mecanisme: bijvoorbeeld when (ex is EndpointNotFoundException || ex is CommunicationException)

public class PollyRetryMiddleware
{
    private readonly RequestDelegate _next;
    private readonly AsyncRetryPolicy _retryPolicy;

    public PollyRetryMiddleware(RequestDelegate next)
    {
        _next = next;

        // Define the retry policy: retry 3 times with a 1-second delay between attempts
        _retryPolicy = Policy
            .Handle<YourSpecificException>() // Replace with the specific exception to handle
            .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(1),
            (exception, timeSpan, retryCount, context) =>
            {
                // Log or handle retries (optional)
                Console.WriteLine($"Retry {retryCount} encountered an error: {exception.Message}. Retrying in {timeSpan}.");
            });
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // Execute the next middleware with the retry policy
        await _retryPolicy.ExecuteAsync(async () =>
        {
            await _next(context);
        });
    }
}