Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exercises on Middleware #1

Open
Laoujin opened this issue Jun 20, 2024 · 1 comment
Open

Exercises on Middleware #1

Laoujin opened this issue Jun 20, 2024 · 1 comment

Comments

@Laoujin
Copy link
Member

Laoujin commented Jun 20, 2024

Have a Controller Action method with:

  • Logging the request (url, parameters, route segments etc)
  • try/catch & logging
  • Tracing (took x ms to execute)

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

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

Others:

  • Caching
  • Authentication/Authorization
  • Validation
  • Add additional response headers
  • Content minification
  • Throttling
  • Localization & Internationalization
@Laoujin
Copy link
Member Author

Laoujin commented Oct 15, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant