When writing an application that uses HttpClient I have the same approach as this post, in other words I don't use using and instead use a static HttpClient. I have had no problems with that when I want to communicate with only one server. (I set the Ip address as BaseAddress
and proceed)
Now I have the same problem as this question regarding the fact that BaseAddress can not be changed after starting to use the HttpClient.
That question's answers respond with an explanation that it can not be done. You can not change BaseAddress.
So my question (which is different than the linked one so not a duplicate) is what to do if we want to change the ip adress to communicate with other server?
Should we instantiate another HttpClient? (no, we are not going to use using
) How do we correctly proceed from here?
The base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests.
All you have to do is set the BaseAddress on the HttpClient: var httpClient = new HttpClient(); httpClient. BaseAddress = new Uri("https://peterdaugaardrasmussen.com/"); var response = await httpClient.
Generally, you don't want to dispose of HttpClient unless it's used very infrequently. Regular creation and disposal may lead to socket exhaustion.
Instead of creating a new instance of HttpClient for each execution you should share a single instance of HttpClient for the entire lifetime of the application.
As it stands you can't change the base address.
How do we correctly proceed from here?
Do not set the base address and just use the full addresses for the requests.
That way the same client can be used for all requests other wise you would need to create a new client for each base address which will also defeat the advantages of having the single client.
The client factory in asp.net core 2+ has since fixed the problems associated with having multiple clients.
Disposing of the client is not mandatory, but doing so will cancel any ongoing requests and ensure the given instance of HttpClient cannot be used after Dispose is called. The factory takes care of tracking and disposing of the important resources that instances of HttpClient use, which means that HttpClient instances can be generally be treated as .NET objects that don’t require disposing.
One effect of this is that some common patterns that people use today to handle HttpClient instances, such as keeping a single HttpClient instance alive for a long time, are no longer required. Documentation about what exactly the factory does and what patterns it resolves will be available, but hasn’t been completed yet.
Completed documentation Use HttpClientFactory to implement resilient HTTP requests
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