Stop using the HttpClient the wrong way in .NET

Поделиться
HTML-код
  • Опубликовано: 14 авг 2022
  • Check out my courses: dometrain.com
    Become a Patreon and get source code access: / 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
    NDC Oslo | 26 - 30 Sept | bit.ly/ndcoslo2022workshop
    NDC Sydney | 10 - 14 Oct | bit.ly/ndcsydney2022workshop
    dotnetdays | 20 - 22 Oct | bit.ly/dotnetdays2022workshop
    NDC Minnesota | 15 - 18 Nov | bit.ly/ndcminnesota2022workshop
    NDC London | 23-27 January 2023 | bit.ly/ndclondon2023
    Don't forget to comment, like and subscribe :)
    Social Media:
    Follow me on GitHub: bit.ly/ChapsasGitHub
    Follow me on Twitter: bit.ly/ChapsasTwitter
    Connect on LinkedIn: bit.ly/ChapsasLinkedIn
    Keep coding merch: keepcoding.shop
    #csharp #dotnet #nickchapsas

Комментарии • 230

  • @nickchapsas
    @nickchapsas  Год назад +139

    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 Год назад +14

      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

      @@devtekve1396 Exactly this. Same happened to me.

    • @neilbroomfield3080
      @neilbroomfield3080 Год назад +1

      Flurl

    • @aralyon
      @aralyon Год назад

      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 Год назад

      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

  • @RENAUDADAM
    @RENAUDADAM Год назад +13

    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!

  • @emerynoel567
    @emerynoel567 Год назад +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.

  • @mrcarlpaton
    @mrcarlpaton Год назад +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!

  • @davideglass
    @davideglass Год назад +74

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

    • @nickchapsas
      @nickchapsas  Год назад +32

      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 Год назад +6

      @@nickchapsas Lets hope people read the comments then!

    • @ucheemmanuel9797
      @ucheemmanuel9797 Год назад

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

    • @LiamLagan
      @LiamLagan Год назад +4

      @@davideglass We do.

    • @davideglass
      @davideglass Год назад +1

      @@LiamLagan You are a gentelman and a scholar!

  • @vivekkaushik9508
    @vivekkaushik9508 Год назад +1

    The best channel for C# I have found on RUclips. Thankyou.

  • @CRBarchager
    @CRBarchager Год назад

    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!

  • @johndirksen4617
    @johndirksen4617 Год назад

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

  • @drewkillion2812
    @drewkillion2812 Год назад +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.

  • @octaviandobre
    @octaviandobre Год назад

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

  • @CodewithSaar
    @CodewithSaar Год назад

    Very well explained. Thank you!

  • @ReMx3DIT
    @ReMx3DIT Год назад

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

  • @vifvrTtb0vmFtbyrM_Q
    @vifvrTtb0vmFtbyrM_Q Год назад +14

    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.

  • @revirecepcionista9800
    @revirecepcionista9800 Год назад

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

  • @davestorm6718
    @davestorm6718 Год назад +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!

  • @Aphradity
    @Aphradity Год назад

    Nice job on this explanation Nick.

  • @krishnamurthymadaraboina1556
    @krishnamurthymadaraboina1556 7 месяцев назад

    Your explanation of the concept is very clear.

  • @Whivel
    @Whivel Год назад +1

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

  • @saintinel
    @saintinel Год назад

    Great video Nick, thnx!

  • @yv989c
    @yv989c Год назад +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.

  • @joshodom131
    @joshodom131 Год назад

    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!!

  • @harunmn
    @harunmn Год назад

    beautiful examples, thanks :)

  • @Plankmeister
    @Plankmeister Год назад

    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...

  • @boommonkey111
    @boommonkey111 Год назад

    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 !

  • @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.

  • @amantinband
    @amantinband Год назад

    💯. Thanks for the awesome content 🫶🏼

  • @Code_Bits
    @Code_Bits Год назад

    I was using this, works amazing.

  • @charlesopuoro5295
    @charlesopuoro5295 Год назад

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

  • @richardclarke376
    @richardclarke376 Год назад

    wow, that is really helpful. thanks

  • @ZNaut13
    @ZNaut13 Год назад +2

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

  • @cedricvereecke6108
    @cedricvereecke6108 Год назад

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

  • @chrisvandewouw
    @chrisvandewouw Год назад

    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!

  • @programmerako
    @programmerako Год назад

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

  • @alexclark6777
    @alexclark6777 Год назад

    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 Год назад

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

  • @dmytrk
    @dmytrk Год назад +1

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

  • @stefangranath3841
    @stefangranath3841 Год назад +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.

  • @urbanelemental3308
    @urbanelemental3308 Год назад

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

  • @rade6063
    @rade6063 Год назад

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

  • @spvs84
    @spvs84 Год назад

    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.

  • @injenius21
    @injenius21 Год назад

    Thanks!

  • @urbanelemental3308
    @urbanelemental3308 Год назад

    LOVE IT!

  • @DChristop
    @DChristop Год назад

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

  • @jtucker87
    @jtucker87 Год назад +2

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

  • @brianm1864
    @brianm1864 Год назад +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!!)

  • @moranmono
    @moranmono Год назад

    Thanks a lot

  • @mcdev6868
    @mcdev6868 Год назад

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

  • @adrianspikes6454
    @adrianspikes6454 Год назад

    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!

  • @2u1u
    @2u1u Год назад

    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

  • @mundodolewis5412
    @mundodolewis5412 9 месяцев назад

    great video

  • @arnonoordover4054
    @arnonoordover4054 Год назад

    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.

  • @joshemm4991
    @joshemm4991 Год назад

    thanks, i was just creating new instance always.

  • @maciejgawe4407
    @maciejgawe4407 Год назад

    I was using it already :D

  • @gavinlangley8411
    @gavinlangley8411 Год назад

    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.

  • @souhayelsaid9695
    @souhayelsaid9695 Год назад

    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.

  • @UnbornX69
    @UnbornX69 Год назад +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?

  • @atifsaeedkhan9207
    @atifsaeedkhan9207 Год назад

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

  • @user-ru5ti9tq4w
    @user-ru5ti9tq4w 10 месяцев назад

    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!

  • @megadesty
    @megadesty Год назад +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!

  • @TomaszKosek
    @TomaszKosek Год назад +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 ;)

  • @wandie87
    @wandie87 Год назад

    Great video. Would be interesting to see your proposed solution for implementing nswag api client.
    I have used the IHttpClient method with named http clients.

  • @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.

  • @HomeSlize
    @HomeSlize Год назад

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

    • @nickchapsas
      @nickchapsas  Год назад +1

      I will be using it in my REST API course

  • @skeiths8705
    @skeiths8705 Год назад

    Hi Nick, thanks for sharing the great tutorial to handle HttpClient.
    I am wondering, is there anyway to add new Http header into the existing HttpClient after the DI is initialized?

  • @siavash2176
    @siavash2176 Год назад

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

  • @aracon9721
    @aracon9721 Год назад

    Perfect! I'm just working on a project where I need the HttpClient or two actually. Exactly what I needed :D
    Edit: Actually I'm using RestSharp, I wonder if this works also this way...

  • @jayallard6766
    @jayallard6766 Год назад

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

  • @gregcyrus2739
    @gregcyrus2739 Год назад

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

  • @Sebastian----
    @Sebastian---- Год назад

    nice one

  • @guillermomazzari8320
    @guillermomazzari8320 9 месяцев назад

    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?

  • @yanaraldaghestani6305
    @yanaraldaghestani6305 Месяц назад

    amazing

  • @codeforme8860
    @codeforme8860 Год назад

    If you are retrying an API post or put you should make sure it supports idempotent requests. You don't want to retry make payment with stripe 10 times because the client timed out

  • @verdurakh
    @verdurakh Год назад

    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?

  • @kirillzlobin7135
    @kirillzlobin7135 Месяц назад

    So many stuff to do to make just one api call in C#... Lots of videos showing different 20 line examples on how to do a get call. JS is a ninja

  • @seanc1105
    @seanc1105 Год назад +5

    Microsoft should have just put the HttpClientFactory functionality into the HttpClient code to manage "circuit exhaustion" and DNS caching. Imagine if every library in .NET had to be instantiated with a Factory to deal with problems built into the default library.

    • @MoireFly
      @MoireFly Год назад +1

      At this point, HttpClient should be deprecated, and a replacement API with less foot-shooting likelihood promoted. Alas...
      Unfortunately, this is far from the only IDisposable that's not really (appropriately) disposable, e.g. Task.

  • @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.

  • @ehvlullo
    @ehvlullo Год назад +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.

  • @ramprahalad5579
    @ramprahalad5579 11 месяцев назад

    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!

  • @kippie86
    @kippie86 Год назад +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?

  • @gustavobrasil5722
    @gustavobrasil5722 Год назад

    Hi Nick, great video, I have on question tough. About the dns problem when the connection expires, what if the disconnection didn't come from a timeout, but were disconnected by the server, is there any way to get notified that before doing a new request ?

  • @vladmartian
    @vladmartian Год назад +1

    Temperature is in Kelvin

  • @Time21
    @Time21 Год назад +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?

  • @florianmaul9983
    @florianmaul9983 Год назад +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?

  • @mahesh_rcb
    @mahesh_rcb Год назад +2

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

  • @ibnfpv
    @ibnfpv Год назад

    Great video
    Of curse using this approch
    Also using it with reffit as client library 📖 as it is using the factory in compare to. Rest sharp WDYT? About Restshap way of doing calls in.dot core

  • @justgame5508
    @justgame5508 Год назад

    I’d say the first way (Typed client) seems slightly better as when testing you don’t need to inject an IHttpClisntFactory
    And mock the returned client you want, you can just inject your client directly

  • @petedavis7970
    @petedavis7970 Год назад +1

    "Temperature in... that's not Fahrenheit, is it?" If it is, it's a really, really bad day for Londoners.

  • @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?

  • @cuongme626
    @cuongme626 Год назад

    How would I do this for projects like Specflow? Do I define a httpClientFactory and register it in the built in DI container and then return a httpClient so it can be injected in my classes?

  • @Qushaak
    @Qushaak Год назад

    My scenario. There are more different URLs with different authentication headers in database. Of course, users can add/update/remove these endpoints. Each endpoint is POST method and the content which is sent is also the same.
    When a new message arrives in the application (and is processed), then it should be sent to all defined endpoints (which are currently defined in database).
    How to efficiently send this message to endpoints in parallel using HttpClient?
    Thank you for suggestions.

  • @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?

  • @thetargetthetarget3003
    @thetargetthetarget3003 Год назад

    Great video, I've used IhttpclientFactory multiple times , but I have one issue that I encounter when I'm using it inside a wpf application to call an Api, it seems that the http client cant detect when the internet connection is restored, for now the only solution is to reinstantiate http client each time when the connection is restored, is there any way to configure httpclient to detect internet connection when it is restored while using IhttpclientFactory

  • @dfytq
    @dfytq Год назад

    How to add a outgoing request body logger and incoming response logger?

  • @CYBERTeamOnlineSportTV
    @CYBERTeamOnlineSportTV Год назад

    Hello :D I would like to see video about gRPC and sending large objects between microservices (as base64 or in different format) via gRPC to avoid (in my case) outofmemory exception! Thx )))

  • @isen1
    @isen1 Год назад +4

    🥵🤯😓 Sooooo much to know... Im a beginner watching this blowing my head.

  • @libertyernie
    @libertyernie Год назад +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 Год назад

      Did you find a suitable approach for this?

  • @LCTesla
    @LCTesla 6 месяцев назад

    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.

  • @halahb6113
    @halahb6113 Год назад

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

  • @d3struction61
    @d3struction61 Год назад

    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

  • @AmpDecay
    @AmpDecay Год назад

    I love using IHttpClientFactory and Polly

  • @raagansvlog2491
    @raagansvlog2491 Год назад +1

    How can we do this for .Net framework projects?