What is the purpose of HttpClient.BaseAddress and why can't I change it after the first request

社会主义新天地 提交于 2019-12-06 05:04:49

For (1), a common use case would be a client which interacts with exactly one server. Maybe it's the back-end API that this client was built to use. The exact details will be stored in a config file that the client reads during startup.

We could litter our code with direct accesses to the config, or inject the string read from config into every place that needs to construct a full URL. Or we could just configure the BaseAddress of the HttpClient we're putting into our Dependency Injection container and just let the consuming locations have that object injected. That for me is a somewhat expected use case.

For (2), I don't think there's a technical limitation. I think this is more there to save people from themselves. Since setting a BaseAddress and causing an actual request to go out via e.g. GetAsync are separate actions, it would be unsafe for two separate pieces of code to be doing such a thing at the same time - you could easily get races. So it's easier to reason about multi-threaded programs that may be sharing a single instance of HttpClient if such races aren't allowed in the first place.

2 purposes:

  1. Convenience. If you're calling many endpoints off a single host, and you're managing the base address and endpoint segments as separate strings (very common), it helps you avoid doing ugly string concatenation on every call.

  2. Encouraging best practices. Although making calls via GetAsync, etc. is thread safe, HttpClient has several properties in addition to BaseAddress, such as DefaultRequestHeaders, that are not. Very typically, you want these to be the same for calls to the same host but not for calls to different ones. For this reason, an HttpClient instance per host being called is actually a very good practice. Unless you're calling thousands of different hosts, you don't need to worry about the infamous socket exhaustion problem here. (And even if you were using a singleton, the underlying network stack would need to open a different socket per host anyway.)

So why does specifying a full address on an HttpClient call even work at all? Again, convenience. The address might be coming from an external source or user input, and you wouldn't want to have to break it into pieces in order to use it. But in this case, you are on the hook for thread safety, and those non-thread-safe properties should probably just be avoided entirely.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!