Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

c# - Changing the Base Address of a HttpClient

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...