✅ Best practice usage of HttpClient in .Net Framework 4.5

Hello everyone 👋 hope you’ll. Are having a good day/evening. What is the recommended approach of using http client in a dot net framework 4.5.2 project ? Please note that I’m not able to use dependency injection in this project
5 Replies
Angius
Angius3y ago
"What is the recommended approach to do X? By the way, I can't use the recommended approach." I guess you could create some singleton kind of a class with a static HttpClient If you don't use it much, chances are a single instance of it will be fine. If you use more, you'll need some code that will manage instantiating and destroying more of them
aleteia_learner
aleteia_learnerOP3y ago
like this right ?
private static readonly HttpClient client = new HttpClient();

public void MakeRestCall(string url){
var response = await client.GetAsync(uri);
}
private static readonly HttpClient client = new HttpClient();

public void MakeRestCall(string url){
var response = await client.GetAsync(uri);
}
Currently have 3 classes which uses httpclient, and since each of these make a http request to 3 different baseurl's, does this mean that I will need 3 more static instances of httpclient ?
Hulkstance
Hulkstance3y ago
yup it's the static instance. Nick Chapsas shows that way as well in his video https://www.youtube.com/watch?v=Z6Y2adsMnAA
Nick Chapsas
YouTube
Stop using the HttpClient the wrong way in .NET
Check out my courses: https://nickchapsas.com Become a Patreon and get source code access: https://www.patreon.com/nickchapsas Hello everybody I'm Nick and in this video I will show you why the way you might be using the HttpClient in .NET could be completely wrong and then follow it up by showing you the right way to implement it. Workshops N...
aleteia_learner
aleteia_learnerOP3y ago
when using static instance of an httpclient, does that mean defaultrequestheaders cant be set again ? say if the auth token changes ?
Accord
Accord3y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server