CodexBloom - Programming Q&A Platform

Using IHttpClientFactory with Polly for Resilience in Blazor WebAssembly - implementing Handling scenarios Requests

๐Ÿ‘€ Views: 4 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-04
c# blazor httpclient polly C#

Hey everyone, I'm running into an issue that's driving me crazy. I'm working on a project and hit a roadblock. I've been banging my head against this for hours. I've been banging my head against this for hours. I'm working with issues when using `IHttpClientFactory` with Polly for implementing resiliency in my Blazor WebAssembly application. I've set up a simple retry policy for my HTTP requests, but it seems that exceptions are not being handled as expected. Instead of retrying, I'm getting the original exception thrown, which is causing my UI to freeze until the request times out. Hereโ€™s what I have set up: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddHttpClient<MyService>() .AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(3, _ => TimeSpan.FromMilliseconds(500))); } ``` In my service, I call the API like this: ```csharp public class MyService { private readonly HttpClient _httpClient; public MyService(HttpClient httpClient) { _httpClient = httpClient; } public async Task<string> GetDataAsync() { var response = await _httpClient.GetAsync("https://example.com/api/data"); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } } ``` When I run the code and the API is down, I expect it to retry and eventually show an behavior message. However, I see the following behavior immediately in the console instead: `HttpRequestException: No connection could be made because the target machine actively refused it.` The UI freezes for a few seconds before displaying the behavior. I've tried adding logging to see if the retries are occurring, but it doesn't seem to log anything related to retries. I also checked to ensure that Polly was properly configured and added to the service collection, but thereโ€™s still no change. What am I missing in this configuration? Is there something specific to Blazor WebAssembly that I need to consider since it runs on the client-side? Any insights or suggestions would be greatly appreciated! I'm working on a service that needs to handle this. For context: I'm using C# on Linux. I'd really appreciate any guidance on this. Thanks in advance! I'd really appreciate any guidance on this. Any ideas what could be causing this?