Stop using the HttpClient the wrong way in .NET

Поділитися
Вставка
  • Опубліковано 3 лют 2025

КОМЕНТАРІ • 246

  • @nickchapsas
    @nickchapsas  2 роки тому +149

    Hello everybody, I forgot to mention something in the video. If you add a service with a specific lifetime in the DI container and then you use the typed client versions of AddHttpClient (not the other ones for the IHttpClientFactory) then the service will be rewired as a Transient. If you need a singleton, or even scoped service, use the IHttpClientFactory which will guarantee that.

    • @devtekve1396
      @devtekve1396 2 роки тому +16

      If you re register the service, then the http client configs are lost… I was using aws X-ray and experienced that… the best way to deal with this is really using named clients. So you create the named client on configure, and you inject the factory to your singleton service (or whatever scope you want) and through the factory you get the client just like you did on the end of the video. Do not register the service twice.

    • @davideglass
      @davideglass 2 роки тому +2

      @@devtekve1396 Exactly this. Same happened to me.

    • @neilbroomfield3080
      @neilbroomfield3080 2 роки тому +1

      Flurl

    • @aralyon
      @aralyon 2 роки тому

      Thanks, I was wondering through the video how it works if the WeatherClient is singleton and therefore keeps all the instances for a lifetime, this explains a lot :)

    • @ackrite8139
      @ackrite8139 2 роки тому

      This was actually what let me scroll back in the video a dozen times until I saw your comment 😂 always this DI dark magics in background

  • @Whivel
    @Whivel 2 роки тому +1

    Thanks. I already had an opportunity to use the "new" method.

  • @emerynoel567
    @emerynoel567 2 роки тому +9

    FINALLY I get a Nick Chapsas video where I can say "oh yeah, I knew that 😎"
    At my last job I was the driving force of getting the factory (using named clients) as THE way to use HttpClient. At my current job, it is much more of a struggle, but we will get there.

  • @RENAUDADAM
    @RENAUDADAM 2 роки тому +14

    Hey Nick, great video! I just wanted to say I love that you deliver videos on a constant schedule basically at the same time every week. I know that when I wake up on Monday mornings and am getting geared up for work I have a Nick Chapsas video to get my head in the zone, inspired to code. Thank you for creating these videos!

  • @vivekkaushik9508
    @vivekkaushik9508 2 роки тому +1

    The best channel for C# I have found on UA-cam. Thankyou.

  • @injenius21
    @injenius21 2 роки тому

    Thanks!

  • @mrcarlpaton
    @mrcarlpaton 2 роки тому +1

    Ive watched so many of your videos brother, this was the first time I was already doing what you suggest. Thank you so much for you content, it helps me all the time!

  • @davestorm6718
    @davestorm6718 2 роки тому +4

    Great video! I wanted to note that, for Blazor components - with a code behind that is a partial class, instead of:
    private readonly IHttpClientFactory _httpClientFactory;
    public MyClass(IHttpClientFactory httpClientFactory)
    {
    _httpClientFactory = httpClientFactory;
    }
    you use:
    [Inject]
    public IHttpClientFactory _httpClientFactory { get; set; }
    Hope this helps the Blazor folks!

  • @drewkillion2812
    @drewkillion2812 2 роки тому +7

    I've been using IHttpClientFactory since I learned about the reason behind it. So many developers are unaware of its need and the problem it solves still.

  • @davideglass
    @davideglass 2 роки тому +77

    Note you have introduced a small unintended change in your app when you do AddHttpClient

    • @nickchapsas
      @nickchapsas  2 роки тому +33

      Good point, totally forgot to mention that after I got sidetracked with the IHttpClientFactory example. Will add it in the pinned comment thanks.

    • @davideglass
      @davideglass 2 роки тому +6

      @@nickchapsas Lets hope people read the comments then!

    • @ucheemmanuel9797
      @ucheemmanuel9797 2 роки тому

      Can I contact you on any social media? Would really love to learn and understand .net

    • @LiamLagan
      @LiamLagan 2 роки тому +4

      @@davideglass We do.

    • @davideglass
      @davideglass 2 роки тому +1

      @@LiamLagan You are a gentelman and a scholar!

  • @ReMx3DIT
    @ReMx3DIT 2 роки тому

    Can't believe I had this right before Nick telling me. I'm improving! Thanks Nick!

  • @ZNaut13
    @ZNaut13 2 роки тому +2

    The most asked question on the job interviews so far. I’ve been asked 4 times about it during this summer.

  • @Plankmeister
    @Plankmeister 2 роки тому

    It's such a relief to find out I've been doing it the right way. I was a bit nervous there for a while...

  • @johndirksen4617
    @johndirksen4617 2 роки тому

    Best explanation I've seen, this is excellent. This problem has been painful! Subscribed, can't wait to learn about Polly.

  • @octaviandobre
    @octaviandobre 2 роки тому

    Wow, I am amazed at how many videos you make. Respect.

  • @krishnamurthymadaraboina1556

    Your explanation of the concept is very clear.

  • @yv989c
    @yv989c 2 роки тому +4

    Thanks for bringing awareness to this sometimes silent issue. I would say the confusion have been due to how this type has evolved between runtimes over the years. Everything you explained can be found in the official docs around HttpClient. Microsoft have done a great job there.

  • @krishnayele5639
    @krishnayele5639 Рік тому

    Awesome, I am trying to edit already existing code and this gives me an idea why the things are the way they are.

  • @revirecepcionista9800
    @revirecepcionista9800 2 роки тому

    You saved my life! Thank u so much! Greetings from Mexico!

  • @CRBarchager
    @CRBarchager 2 роки тому

    In my current (newest) project I used the static verstion you descriped. I've updated it to instanciate it from the builder without any problems. Thank you for sharing!

  • @programmerako
    @programmerako 2 роки тому

    for the first time Nick discuss a topic I know and in my birthday

  • @charlesopuoro5295
    @charlesopuoro5295 Рік тому

    Thanks a whole lot for this clear explanation as to how to properly utilize HttpClient for API calls.

  • @memoryleakerz
    @memoryleakerz 6 місяців тому

    damn, what knowledge and presentation, SUBSCRIBED!

  • @brianm1864
    @brianm1864 2 роки тому +6

    We use the AddHttpClient method a lot in our services, although lately we have been moving to using Flurl and injecting an IFlurlClientFactory, which you then use to request a client. The concept, as far as I can tell, is the same as injecting an IHttpClientFactory. But your comment about IHttpClientFactory and its integration with Polly has me intrigued! I may have to check that out (unless you want to do a video for it next!!)

  • @stefangranath3841
    @stefangranath3841 2 роки тому +8

    I'm using HttpClientFactory with named clients and poly (because I learnt it from you) in the next integration to be deployed. Made things so much cleaner, especially as I use multiple clients with different header configurations. I had no clue about the DNS issue, feels like I dodged a bullet here.

  • @boommonkey111
    @boommonkey111 2 роки тому

    Hi Nick, well done on getting signed up on all the conferences, you deserve it as you are a fantastic ambassador... i hope they are looking after you :) Business Class I mean !

  • @Aphradity
    @Aphradity 2 роки тому

    Nice job on this explanation Nick.

  • @dmytrk
    @dmytrk 2 роки тому +1

    Learned this from Microsoft Docs, so used it like this already😃

  • @joshodom131
    @joshodom131 2 роки тому

    Going to have to try this, I just had to build an in house authentication api and we were wondering exactly how to handle the client component of it. Thanks as always!!

  • @jtucker87
    @jtucker87 2 роки тому +2

    Named HTTPClients with Polly here! But it took some massive headaches before I learned to do it that way.

  • @vifvrTtb0vmFtbyrM_Q
    @vifvrTtb0vmFtbyrM_Q 2 роки тому +15

    I want to warn you against using a static HttpClient. You will have problems if:
    1. Multi-threaded use.
    2. Outgoing connection to different endpoints.
    3. Use different headers.
    HttpClient has internal state (fields). And if different headers are initialized in different threads, you will either have dirty data errors or even NREs.

  • @megadesty
    @megadesty 2 роки тому +2

    I'm using the HttpClient with the factory by coincidence because I wanted to mock it in unit tests. I'm glad this is also the recommended way, thanks for explaining why!

  • @chrisvandewouw
    @chrisvandewouw 2 роки тому

    What a coincedent, as today I was developing a reusable library which needs to connect the httpclient with a client certificate. The problem I was facing is that the certificate to use on production needs to be fetched from azure keyvault and for local development I don't want to use the keyvault (that will be done with User Secrets). Actually I don't want to have a dependency on the keyvault packages in the reusable library at all.
    I was already looking into the IHttpClientFactory and your video will surely help me tomorrow finalize this job. Thanks!

  • @alexclark6777
    @alexclark6777 2 роки тому

    This is properly useful information; like many I was just instantiating and using a single HttpClient instance without considering things like DNS lifetimes. This also reminds me why I have a love/hate relationship with DI - it makes things easier in a lot of instances, but sometimes I feel like it hides a bit too much and lacks intuitiveness.
    Great video, and loved your NDC talk about Minimal APIs by the way - I'm a convert!

    • @PK-ht1mi
      @PK-ht1mi 2 роки тому

      Why? An object that consumes a HTTPClient shoulnd't be concerned with all that stuff.

  • @cedricv-p9z
    @cedricv-p9z 2 роки тому

    this is a great subject. Can't wait to learn more about polly

  • @DChristop
    @DChristop Рік тому

    Γειά σου βρε Χρήστο με τους μοναδικούς σου τρόπους!!!

  • @adrianspikes6454
    @adrianspikes6454 2 роки тому

    Great video Nick. And I was glad to hear u shout out Raw Coding in a earlier vid. I subscribe to both of ur channels as well as IAmTimCorey, Les Jackson and Shiv Kumars' So u think u know C#. Keep up the great work. Oh and very glad to see u a NDC Conferences!

  • @ΑλέξανδροςΝτόνας

    You're the official author of C# compiler source and you're the only one because you wrote the compiler yourself! That explains a lot no other way around that you know so much!

  • @2u1u
    @2u1u 2 роки тому

    Every company I've worked for uses restclient. I've not looked at how it's used under the hood either. But I believe earlier iterations of restclient suffered some of these issues. You've explained and shared things here I was none the wiser. Thank you

  • @urbanelemental3308
    @urbanelemental3308 2 роки тому

    Glad I paid attention to the correct way years ago. Had to because I was writing custom handlers.

  • @kebabfoto
    @kebabfoto Рік тому

    Damn this was well invested 10 minutes of watch time. Subscribing and i'll probably become a patreon to look at the code in more detail.

  • @Code_Bits
    @Code_Bits 2 роки тому

    I was using this, works amazing.

  • @atifsaeedkhan9207
    @atifsaeedkhan9207 2 роки тому

    Thanks, I have never thought earlier to use the httpClient the way you taught us. Thanks once again.

  • @rade6063
    @rade6063 2 роки тому

    Great video. Cant wait for the microservices series (in case it is stil planned).

  • @mahesh_rcb
    @mahesh_rcb 2 роки тому +2

    How can the same be achieved in .net framework 4.8 and below ..
    Any suggestions

  • @gregcyrus2739
    @gregcyrus2739 2 роки тому

    Ouuugh.. lucky you started to mention the Factory @4:44 (feared that Best Practice has changed again;)

  • @TomaszKosek
    @TomaszKosek 2 роки тому +1

    Nick great video but you missed the most important thing. Why you can get error pool is exhausted. It will definitely help people understand why it's important to reuse HttpClient and what exactly happened when you do not ;)

  • @raagansvlog2491
    @raagansvlog2491 2 роки тому +1

    How can we do this for .Net framework projects?

  • @mcdev6868
    @mcdev6868 2 роки тому

    This came in handy, I am just about to implement HTTP functionality for my app.

  • @markhenderson5283
    @markhenderson5283 7 місяців тому

    I'm big into typed clients. That is the best way to do it most of the time in my opinion.

  • @amantinband
    @amantinband 2 роки тому

    💯. Thanks for the awesome content 🫶🏼

  • @CodewithSaar
    @CodewithSaar 2 роки тому

    Very well explained. Thank you!

  • @spvs84
    @spvs84 2 роки тому

    Thanks Nick for a great video.. it would be great if you could do a follow-up video about shared CookieContainer issue and how to work around that.

  • @saintinel
    @saintinel 2 роки тому

    Great video Nick, thnx!

  • @harunmn
    @harunmn 2 роки тому

    beautiful examples, thanks :)

  • @florianmaul9983
    @florianmaul9983 2 роки тому +2

    But how is this unit testable? Does the CreateClient method in the factory return an interface or the HttpClient itself? I use Refit which provides a Library that uses IHttpclientfactory behind the scenes. What do you think is Refit a good way to go this time?

  • @UnbornX69
    @UnbornX69 2 роки тому +4

    Great video! One thing I've wondered when using IHttpClientFactory is what the best practices are when it comes to guarenteeing that a named client, which is required by a service, has actually been configured.
    Currently I'm using an extension method which registers both the named client and the service that requires it - but I'm wondering if there is a better way?

  • @guy6311
    @guy6311 2 роки тому +2

    8:39 Could you dispose the HttpClient returned by CreateClient?
    using var client = _httpClientFactory.CreateClient("weatherapi");

    • @nickchapsas
      @nickchapsas  2 роки тому

      Yeah that’s totally fine

    • @SaPpHiRe051918
      @SaPpHiRe051918 5 місяців тому

      you can but you must not. HttpMessageHandler will take care the lifetime better than what you will.

  • @libertyernie
    @libertyernie 2 роки тому +5

    What's the best way to make HTTP requests from within a library (distributed as a .dll or on NuGet), where the application using it is not necessarily a web application and might not have dependency injection available? I imagine there's some way to let the consumer of the library provide their own objects for request handling, but I'm not sure what the most sensible defaults should be if they don't do so (or, should they be forced to do so by making it a required argument?)

    • @Gobba61
      @Gobba61 2 роки тому

      Did you find a suitable approach for this?

  • @jayallard6766
    @jayallard6766 2 роки тому

    Great video, thanks. When you create the named client from the factory, shouldn't it have a USING? (9:07 line 25)

  • @15wojto
    @15wojto Рік тому

    Fine. But what if client is separate application in different project?

  • @joshemm4991
    @joshemm4991 2 роки тому

    thanks, i was just creating new instance always.

  • @AmitP-o3u
    @AmitP-o3u Місяць тому

    Excellent Video. Is it possible to provide the code as well.

  • @arnonoordover4054
    @arnonoordover4054 2 роки тому

    In a project I coded for we used named httpclients. I refactored that to use typed httpclients and also configured a polly retry policy in the startup for one of the httpclients. The basic auth username and password are also configure in the startup for one of de httpclients that needed to login.

  • @souhayelsaid9695
    @souhayelsaid9695 2 роки тому

    Thank you for this Great video. For me i use Refit with HttpClientFactory instead, it's a library provides a type-safe wrapper for interacting with HTTP-based APIs.

  • @David-iq1kd
    @David-iq1kd Рік тому +2

    If you are requesting data from multiple APIs, would you create separate HttpClients each with their own base url, or still a single HttpClient that can call any url?

  • @richardclarke376
    @richardclarke376 2 роки тому

    wow, that is really helpful. thanks

  • @siavash2176
    @siavash2176 2 роки тому

    Please create a video on proper usage of Polly and how you are using it.

  • @XMaverick20
    @XMaverick20 6 місяців тому

    Is there an equivalent for smtpclient that lets you specify max pooled connections?

  • @guillermomazzari8320
    @guillermomazzari8320 Рік тому

    Thanks for sharing! So I can have as many http-named or typed clients in my program.cs and use them wherever I need them in my app?

  • @norbertcsibi7720
    @norbertcsibi7720 5 місяців тому

    And how do you make that Wheather service testable? E.g Test that once we invoked the method that returns the data, the http got called once for example?

  • @zlarak
    @zlarak 2 роки тому +1

    I'll heavily advocate for using Refit, as long as you don't mind the extra package (which is a completely valid reason to not use it), I don't see any common case where you couldn't use it. (Please correct me if you do !)
    It's completely abstracting all these concerns, which IMO should be abstracted by the Framework in the first place and gives you less code to write to handle deserialization / throwing exceptions.
    + It adds no complexity when pairing it with Polly.
    It's just great all around.

    • @nickchapsas
      @nickchapsas  2 роки тому +1

      Yeah I use Refit as well, but it’s good to know how things are wired out or should be wired up behind the scenes

    • @zlarak
      @zlarak 2 роки тому

      @@nickchapsas It is, for sure !
      But not having to think about it on every new project is such a time/worry saver.
      Anyways, thanks Nick for your great work !

  • @rfphill
    @rfphill Рік тому

    Curious how would I unit test that client class if the httpclient is a private property?

  • @Nekrokon
    @Nekrokon Рік тому +1

    I'm a realive new Junior System Engineer. I've used some of this stuff in my code to connect to an API.
    (It works, but there is always room for improvement, right?)
    And now I'm sitting here, don't understanding a single word. I don't even understand which problem this solves. I feel dumb. ._.

    • @Nekrokon
      @Nekrokon Рік тому

      Ok, now i got it. I showed it to my colleague, and EXPLAINED what the video is about.
      ...so I reallized, I understood the point.
      Creating an instance of a httpClient ONCE and REUSE it, instead of building everytime a new client can improve the performance.
      PS: Seems I'm not dumb, yay :3 xD

  • @maciejgawe4407
    @maciejgawe4407 2 роки тому

    I was using it already :D

  • @samehq6556
    @samehq6556 9 місяців тому

    Question: In some cases I had to bypass some ssl certificate using a client handler, the handler goes in the constructor of the httpclient, so, how to incorporate that in this example

  • @zohaibshahzad3680
    @zohaibshahzad3680 Рік тому

    please create video on blazor vs react native. I love to work with c#. I am also learning javascript for nodjs . how would take the market demand c# as compare to javascript?

  • @d3struction61
    @d3struction61 2 роки тому

    Hi,
    What's the difference between using GetFromJsonAsync vs using
    ReadAsStreamAsync and then working with the stream either via stream-reader or by deserializing the stream directly with JsonSerializer.Deserialize(stream)
    Is there any performance/memory usage difference between the two approaches?
    Thanks

  • @urbanelemental3308
    @urbanelemental3308 2 роки тому

    LOVE IT!

  • @ramprahalad5579
    @ramprahalad5579 Рік тому

    Hi @Nick. Great video. Just had a quick question on this. You don't need that AddSingleton when you added the line AddHttpClient line in program.cs, right? Because that AddHttpClient will register the OpenweatherClient type in DI as transient, right? Can you please confirm? Also, if I have a separate class library services project which my API project calls and all my HttpClient calls are in the services layer, what is the best way to configure/ inject HttpClient to the service layer classes? Thanks!

  • @gavinlangley8411
    @gavinlangley8411 2 роки тому

    I use a slightly different method. I use an explicit factory lambda (mainly for compile time type checking) and in that factory use the httpclientfactory to create the named httpclient to pass to the class keeps all the factories together. Works well.

  • @halahb6113
    @halahb6113 2 роки тому

    Thanks a lot. but I have a question. If an API requires a Token, How can I add one in Startup file ?

  • @mundodolewis5412
    @mundodolewis5412 Рік тому

    great video

  • @kippie86
    @kippie86 2 роки тому +1

    So what's the set-up when you want to use custom HttpClientHandlers? Is it simply more configuration for your services? Or would you be using a custom factory for that?

  • @VennieVin
    @VennieVin 2 роки тому

    at 3:55 you said "If the DNS DTL is expired..." what is DTL referring to here? Many thanks!

    • @nickchapsas
      @nickchapsas  2 роки тому

      Sorry I said TTL, not DTL. TTL is Time To Live

  • @lifehacks1-xp
    @lifehacks1-xp Рік тому

    Hi Nick,
    Do you know if setting the RequestTimeout for a HttpRequestMessage object will always be honored by the server or not?
    Sample code:
    var request = new HttpRequestMessage();
    request.Method = HttpMethod.Post;
    request.RequestUri = new Uri(url);
    request.Properties["RequestTimeout"] = timeout;
    I was working on some task and I stubmbled on this when I was doing some research regarding request timeout:
    GPT:
    "Yes, the method MakePost you've defined will use the timeout specified in the TimeSpan argument to set a timeout for the HTTP request. Specifically, it sets the timeout using the request.Properties["RequestTimeout"] property.
    The timeout value is passed as a TimeSpan and is used to set the request timeout. When making the HTTP request, the timeout will be applied, and the request will timeout if it exceeds the specified duration.
    Keep in mind that setting a timeout on the HttpRequestMessage doesn't guarantee that the server will honor it. The server may choose to ignore the client's timeout and handle the request in its own time."

  • @abexperience7555
    @abexperience7555 5 місяців тому

    @nick How HttpClient was used in times of .net mvc when .net core is not introduced

  • @Time21
    @Time21 2 роки тому +1

    How do you see basic implementation of classes like HttpClient in this video? I have seen you cycle through code.
    Or is this an extension on Rider of how things work?

  • @plontulublalulu
    @plontulublalulu 8 місяців тому

    What is “circuit exhaustion”? Or am I mishearing

  • @softwaretitbits5849
    @softwaretitbits5849 Рік тому

    I wonder if there is a clean way to access the config in AddHttpClient method.

  • @ehvlullo
    @ehvlullo 2 роки тому +3

    That DNS issue on static or singleton normal new() clients has a nasty failure mode. Everything working fine for weeks and then suddenly not anymore. Bit me in the rear once when I knew a little less about this stuff.

  • @HomeSlize
    @HomeSlize 2 роки тому

    Great video. Polly is such a great tool and time saver. Are you using it in any of your courses?

    • @nickchapsas
      @nickchapsas  2 роки тому +1

      I will be using it in my REST API course

  • @srieen100
    @srieen100 Рік тому

    Good one nick, wondering is there any best way to call SOAP service like similar fashion ? taking advantage of Httpclientfactory ? I believe calling SOAP services will have the same impact on connections if its not handled properly.

  • @jimhart5797
    @jimhart5797 2 роки тому

    What are best practices for the named clients? Should there always be a specified name? Should it be 1 name per base URL?

    • @nickchapsas
      @nickchapsas  2 роки тому +1

      It really depends. For example you might have one client for the whole api and that’s fine but then you might wanna have two named clients for the same api but one configured with service to service access while the other one has some other form of access. As long as the httpclient is short lived, you can go as flexible as you want

  • @LCTesla
    @LCTesla Рік тому

    I usually use the latter approach of injecting IHttpClientFactory, but I don't like defining the BaseUrl and default request headers in a completely different place as the rest of the logic, so I'll do that in the constructor. I also have a nitpicking code analyzer that complains about hardcoded urls so that will be coming from IConfiguration.

  • @buyanimhlongo2414
    @buyanimhlongo2414 2 роки тому

    What if you have different baseUrl's calling different API's?

  • @ahmedma527
    @ahmedma527 2 роки тому

    Thanks for the great content. What if I have like 20 services? I cannot inject the client in each one of them one by one. So, in that case, what is the best approach?

    • @nickchapsas
      @nickchapsas  2 роки тому +1

      Inject the IHttpClientFactory and get them as named clients as shown in the video

  • @F1nalspace
    @F1nalspace 2 роки тому

    I have always used HttpClient with the using pattern. Good to know that there is a factory solution for that... can this be used with Winforms / WPF as well?

  • @verdurakh
    @verdurakh 2 роки тому

    Good video, I've been using the IHttpClientFactory already but a non specified one, just using the AddHttpClient(). Is there any drawback except that you need to configure base url etc for it each time you use it?

  • @moranmono
    @moranmono 2 роки тому

    Thanks a lot