简体   繁体   中英

What is the advantage of setting `BaseAddress` property of `HttpClient`

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:

  1. Create a singleton class for HttpClient and use that for every call by passing API URIs in get/post/put methods.
  2. create a singleton class for 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.

How about option 3: One HttpClient instance per API (domain) being called. It's a little easier to implement than option 2, still allows you to use a different set of stateful properties ( DefaultRequestHeaders , etc.) per API, and still minimizes the number of open sockets lying around, avoiding this infamous problem . This would be my recommendation.

BaseAddress exists solely so you can use relative URIs instead of absolute URIs for individual requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM