Pathoschild / FluentHttpClient

A modern async HTTP client for REST APIs. Its fluent interface lets you send an HTTP request and parse the response in one go.
MIT License
345 stars 52 forks source link

Change default behavior for server errors #106

Closed brunocampiol closed 2 years ago

brunocampiol commented 2 years ago

Hi,

I am trying to find a way to change default behavior "By default the client will throw ApiException if the server returns an error code"

I know I can easily change the current and next http calls to not throw exceptions by following the example here https://github.com/Pathoschild/FluentHttpClient#handle-errors

But I would like to setup it in startup.cs so that I dont need to manully change it on every class (and every client) that needs to use http.

Any ideias here? Thanks

Pathoschild commented 2 years ago

Hi! Since you have a Startup.cs, I assume you're working on an ASP.NET Core app? If so you can use dependency injection to configure the client in one place.

You can either create a common HTTP client and inject it into your controllers or other classes that need it:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped<IClient>(_ => new FluentClient().SetOptions(ignoreHttpErrors: true));
    }
}
public class SomeController : Controller
{
    private readonly IClient HttpClient;

    public SomeController(IClient httpClient)
    {
        this.HttpClient = httpClient;
    }

    public async Task<ActionResult> Any()
    {
        var result = await this.HttpClient.GetAsync<TResult>("https://...");
        ...
    }
}

Or if you want to configure multiple HTTP clients, you can add an interface which builds clients and pass that in through dependency injection instead:

public interface IClientFactory
{
    IClient GetClient(string baseUrl);
}

Let me know if anything is unclear or doesn't work for your use case!

brunocampiol commented 2 years ago

HI thanks a lot for replying and sorry to delay on feedback.

Yes, I am using net core 3.1 for a web api application. I've tried to follow but I guess I have some differences between the pure FluentHttpClient and the one used in the company. But that's a great answer.

Let me get back to the people who wrote this code. I'll let you know if I need more info.