Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
556 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...