June 03 2024
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
[Route("getUser/{id}")]
[HttpGet]
public ActionResult GetUser(int id)
{
Random random = new Random();
var failEdge = random.Next(1, 50);
if (id < failEdge)
{
Console.WriteLine("I'm returning Success - 200");
return Ok();
}
Console.WriteLine("I'm returning Error - 500");
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
public class ClientRetryPolicy
{
public AsyncRetryPolicy<HttpResponseMessage> JustHttpRetry { get; set; }
public AsyncRetryPolicy<HttpResponseMessage> HttpRetryWithWaiting { get; set; }
public AsyncRetryPolicy<HttpResponseMessage> ExponentialHttpRetry { get; set; }
public ClientRetryPolicy()
{
JustHttpRetry = Policy.HandleResult<HttpResponseMessage>(
response => !response.IsSuccessStatusCode)
.RetryAsync(3);
HttpRetryWithWaiting = Policy.HandleResult<HttpResponseMessage>(
response => !response.IsSuccessStatusCode)
.WaitAndRetryAsync(3, attempt => TimeSpan.FromSeconds(5));
ExponentialHttpRetry = Policy.HandleResult<HttpResponseMessage>(
response => !response.IsSuccessStatusCode)
.WaitAndRetryAsync(3,
attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)));
}
}
[HttpGet]
[Route("returnUser/{id}")]
public async Task<ActionResult> ReturnUser(int id)
{
string apiURL = $"https://localhost:7071/api/User/getUser/{id}";
var response = await _retryPolicy.HttpRetryWithWaiting.ExecuteAsync(() =>
_client.GetAsync(apiURL));
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success 200");
return Ok(response);
}
else
{
Console.WriteLine("Error 500");
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
1. Design Patterns that Deliver
This isn’t just another design patterns book. Dive into real-world examples and practical solutions to real problems in real applications.Check out it here.
Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.
Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.
Join 14,250+ subscribers to improve your .NET Knowledge.
Subscribe to the TheCodeMan.net and be among the 14,250+ subscribers gaining practical tips and resources to enhance your .NET expertise.