We call several APIs of multiple domains in our project using HttpClient
. I am creating a common HttpClient
to be used for all these API calls. I am confused between two approaches to implement this:
HttpClient
and use that for every call by passing API URIs in get/post/put
methods.HttpClientHandler
which will be shared among all HttpClient
s and create one HtppClient
for each domain by setting the BaseAddress
property. Now we can call the APIs by passing the relative paths in get/post/put
methods.Which one is the better approach?
Is there any benefit of presetting the BaseAddress
? If not, why is this property provided?
If you choose option 1, the BaseAddress
of course should not be used, as you'd keep overwriting it and you'd have to avoid two threads updating it before one of them has had a chance to send its request.
If you choose option 2, you can configure your HttpClient
per API once (for instance, read BaseAddress
and Timeout
from a configuration file). Relative uri's can then be supplied without having to prepend the base address for each request.
Which is better I guess depends on whether you want to be able to configure properties such as Timeout
or MaxResponseContentBufferSize
for all APIs (option 1) or per API (option 2), I don't have a definitive "this one is better" answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With