The RIGHT Way To Use HttpClient In .NET

  Рет қаралды 50,688

Milan Jovanović

Milan Jovanović

Күн бұрын

Get the source code for this video for FREE → the-dotnet-weekly.ck.page/htt...
☄️ Master the Modular Monolith Architecture: bit.ly/3SXlzSt
📌 Accelerate your Clean Architecture skills: bit.ly/3PupkOJ
🚀 Support me on Patreon to access the source code: / milanjovanovic
The easy way to make HTTP requests in .NET is to use the HttpClient to send those requests. And it's a great abstraction to work with, especially with the methods supporting JSON payloads and responses. Unfortunately, it's easy to misuse the HttpClient. Port exhaustion and DNS behavior are some of the most common problems. So in this video, I'll show what you need to know about working with HttpClient correctly.
The Right Way To Use HttpClient In .NET
www.milanjovanovic.tech/blog/...
Join my weekly .NET newsletter:
www.milanjovanovic.tech
Read my Blog here:
www.milanjovanovic.tech/blog
Subscribe for more:
/ @milanjovanovictech
Chapters
0:00 The naive way to use HttpClient
1:10 Why is this a problem?
2:05 Using the IHttpClientFactory
3:34 Adding configurability with named clients
5:54 Strong typing with typed clients
9:17 Why you should avoid typed clients in Singleton services

Пікірлер: 123
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
Get the source code for this video for FREE → the-dotnet-weekly.ck.page/httpclient
@balakrishnan-gf9rw
@balakrishnan-gf9rw 7 ай бұрын
Hi Milan, I have a correlation Id in my web api. I used typed http client in mvc core 6 application. So in that case how to pass x-correlation Id in all my web API from client. Kindly suggest me..
@davearkley7014
@davearkley7014 11 ай бұрын
I've been using named clients, but like the idea of strongly typed clients so may try them out. One advantage of being able to apply configuration once is that you can add Polly retry policies and they will be used for all instances of the named/typed client.
@zfold4702
@zfold4702 11 ай бұрын
Where is your post?
@metaltyphoon
@metaltyphoon 11 ай бұрын
Strongly typed and singletons have problems, so watch out.
@davearkley7014
@davearkley7014 11 ай бұрын
@@zfold4702 ?
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
Named clients are awesome
@hamitkarahan2973
@hamitkarahan2973 11 ай бұрын
Last part was very nice Milan. Many thanks. I preferred named clients many times in projects. I didn't prefer typed clients because I was a little afraid to delve into this lifetime issues when my services are singleton. I am just basically calling CreateClient method in my infra layer with a using() block. This approach didn't give me any problem so far in production.
@PippiTheLongSock
@PippiTheLongSock 11 ай бұрын
I think you shouldn't manually dispose the instance. I am pretty sure the framework does that automatically.
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
I agree, if it works don't fix it. Right?
@hamitkarahan2973
@hamitkarahan2973 11 ай бұрын
@@MilanJovanovicTech Yesss 😁
@csegyud
@csegyud 11 ай бұрын
It was a nicely built overview. Thank you!
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
Glad you liked it!
@ArnonDanon
@ArnonDanon 11 ай бұрын
Great content as always Milan...thank you🤴🏻
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
You're welcome!
@niezebenmansour3736
@niezebenmansour3736 11 ай бұрын
Thank you for the effort in this video!
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
You're welcome :)
@vibes992000
@vibes992000 11 ай бұрын
Must awaited video. Thanks.
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
Hope you enjoyed it!
@kodindoyannick5328
@kodindoyannick5328 4 ай бұрын
Very good content! Thanks Milan.
@MilanJovanovicTech
@MilanJovanovicTech 4 ай бұрын
You're very welcome!
@JamesSecretofski
@JamesSecretofski 11 ай бұрын
Thanks for the infiniteTimeSpan. Cool tip 👍
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
Don't mention it 😁
@astroGTC
@astroGTC 11 ай бұрын
Great !! keep the good work !
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
Thanks, will do!
@mylesdavies9476
@mylesdavies9476 11 ай бұрын
Nice, have been working with typed clients for a while and find it to be a good approach. The only thing I do differently is inject configuration into the typed client and assign any required headers with the constructor, keeping the configure services nice and clean.
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
I think it's better to do the common things inside of AddHttpClient
@mylesdavies9476
@mylesdavies9476 11 ай бұрын
@@MilanJovanovicTech fair enough, any particular reason?
@JUTO_MTL
@JUTO_MTL 11 ай бұрын
I do exactly the same because i didnt figure out how to retrieve configuration with Option Pattern. I get null from the IConfiguration inside the HttpClient Configuration method. If someone have any idea
@toragodzen
@toragodzen 11 ай бұрын
Hi, great video! I've just subscribed and I want to ask about the difference between the EShop and Gatherly projects, which one is better to learn from?
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
They're slightly different, cant' say one is better than the other
@Javilingys
@Javilingys 7 ай бұрын
What about using Transient HttpClient service inside Scoped Services? Its ok?
@MilanJovanovicTech
@MilanJovanovicTech 7 ай бұрын
No scoped services were used here
@diogosilva3637
@diogosilva3637 11 ай бұрын
Great explantion! Will you make a tutorial about Refit? Thanks!
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
Perhaps, I like that library. Maybe to compare it with HttpClient
@d3vil5oldier
@d3vil5oldier 11 ай бұрын
That's exactly what i was looking for, thanks Milan. Just one question, where do you think those typed clients belong to - Application layer or whatever?
@jaomartins1994
@jaomartins1994 11 ай бұрын
Infra
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
HttpClient could lead you to place it in Infrastructure You could create an interface in Application, however
@user-sy8ld9be8j
@user-sy8ld9be8j 8 ай бұрын
Great Video Milan! Do you have a video showing how you would unit test this pls? (unit test IHttpClientFactory).
@MilanJovanovicTech
@MilanJovanovicTech 8 ай бұрын
I don't yet, sadly. But I would take a look at MockHttp: github.com/richardszalay/mockhttp
@grm360
@grm360 11 ай бұрын
Nice content as always! Could you make a video on how to use Swagger documentation with minimal api?
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
What's to be covered there?
@Lazzerman42
@Lazzerman42 11 ай бұрын
Thanks! Very well explained and clear code examples! I use the RestSharp for know - because it has support for oAuth1(I need it for an old smartHome device). Are there any helpers for oAuth1 and HttpClient?
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
I am not sure, to be completely honest
@wdorsett84
@wdorsett84 11 ай бұрын
Great video! Thank you! Just to confirm when using named clients, the concern over transient vs singleton lifestyles isn't a concern? It's just with typed clients?
@Sanabalis
@Sanabalis 11 ай бұрын
Correct. Since you use a factory to create the named client inside the method each time you invoke it, the lifetime of the class instance is not a factor at all. This is true only if the named client is created inside the method. However, should you create (and capture) named clients inside the constructors, you will effectively introduce the same issues as when using the typed client. Capture the factory instead.
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
Yes, since with named clients you create an instance and dispose of it. If you capture the client in a field, you have a similar issue
@vishalsaini-py4yd
@vishalsaini-py4yd 11 ай бұрын
Great video....can you please tell how I can configure multiple http client having different token mechanism and adding different authorisation header in each separate request.
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
You can use a delegating handler for each client
@Ram92026z
@Ram92026z 11 ай бұрын
Hi @Milan. This was an absolute great video and I am learning a ton from this channel and so, thank you. Hey, how can I use the above method (the 3rd way you describe in the above video) if I am working off of a class library project and I need to use httpClient within it. Basically, all my API calls are in a class library project. Is there an optimal way of using httpClient in it because I am worried about port exhaustion? Thanks
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
If you can create one HttpClient, pass it a SocketsHttpHandler instance at creation with some connection lifetime, and store it in a static field so that it's long-lived - that should suffice
@ramprahalad5579
@ramprahalad5579 11 ай бұрын
@@MilanJovanovicTech , got it! It is that oldish pattern of using the HttpClient I guess. Thanks a lot!
@VascoFernandesBuenoJunior
@VascoFernandesBuenoJunior 11 ай бұрын
O think you need to make another video explaining how to add retry using Polly. I recomend to use Backoff.DecorrelatedJitterBackoffV2 in this case.
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
Will do, great suggestion
@floralb5317
@floralb5317 10 ай бұрын
Hello Milan, Thank you for amazing content. Something is bothering me regarding the configurations you need for a HttpClient. Let's say that you have some configuration stored in Azure Key Vault/Azure SQL Database, and each incoming request to our API has some kind of x-clientId header, how would you handle creating named HttpClient or strong typing HttpClient after retrieving some metadata on Azure Key Vault/Azure SQL? Thank you, keep up the good work :)
@MilanJovanovicTech
@MilanJovanovicTech 10 ай бұрын
I would explore an option of using a DelegatingHandler, to access Key Vault or SQL and get the configuration value.
@DrHeinzDoofenshmirtz
@DrHeinzDoofenshmirtz 8 ай бұрын
Is the last solution for types clients with the lifetime settings a valid and good approach to use? or is it more on the hacky side? I have never stumpled upon it, and I knew almost everything else in the video. Though it was much more well explained than I have read.
@MilanJovanovicTech
@MilanJovanovicTech 8 ай бұрын
MSFT recommendation: learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines
@haskell3702
@haskell3702 11 ай бұрын
Awesome explanation , but I have a doubt how can I Mock the http call using the typed approach? I mean, I want to write a test for GetByUserNameAsync method where the internal httpClient simulates returning 200 and a predefined json
@MilanJovanovicTech
@MilanJovanovicTech 10 ай бұрын
Check this out: github.com/skwasjer/MockHttp
@johntotetwoo
@johntotetwoo 10 ай бұрын
great video but I am wondering how you can configure with token that expires?
@MilanJovanovicTech
@MilanJovanovicTech 10 ай бұрын
DelegatingHandler
@ershadnozari
@ershadnozari 11 ай бұрын
You can inject a httpclientfactory instead of httpclient in a typed client to get around the singleton issue.
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
What's the point of using a typed client then?
@elfatel
@elfatel 11 ай бұрын
Thanks
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
You're welcome!
@AmirHashemZadeh
@AmirHashemZadeh 11 ай бұрын
well done
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
Thanks!
@pmsivakumar
@pmsivakumar 9 ай бұрын
How do you do when you need to fetch the access token dynamically and refresh when it expires with this approach?
@MilanJovanovicTech
@MilanJovanovicTech 9 ай бұрын
Check this out: kzbin.info/www/bejne/laaZp2d6a9aaeqs You need a DelegatingHandler on top of the HttpClient
@WDGKuurama
@WDGKuurama 11 ай бұрын
What i don't understand i why does it hate to make a new instance of the class injecting the httpclient if we could have a singleton do avoid being garbage collected all the time, is there issues with such techniques?
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
A new instance of which class?
@ALOKSHARMAMD
@ALOKSHARMAMD 10 ай бұрын
you said using httpclient in traditional way can exhaust ports in long run, but is this true if we are doing proper dispose by applying using statements?
@MilanJovanovicTech
@MilanJovanovicTech 10 ай бұрын
Yes - you'd end up creating too many handler instances. You want it to be long-lived
@KhinSandarMyint-eq2ks
@KhinSandarMyint-eq2ks 7 ай бұрын
May I know how to add dynamic certificate using HttpClientFactory ? I have to use different certs.
@MilanJovanovicTech
@MilanJovanovicTech 7 ай бұрын
learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/methods-auto/httpclient/httpclient-addcertificate-method
@coder3123
@coder3123 4 ай бұрын
If I were to call API2 from my API1 and the API2 accepts the bearer token that API1 call has is there a way to pass that as header using this method?
@MilanJovanovicTech
@MilanJovanovicTech 4 ай бұрын
You can either create a request object, and set the header. Or set the DefaultRequestHeaders on the HttpClient
@VijayKumar-wy9ku
@VijayKumar-wy9ku 11 ай бұрын
If I'm using 10 different named clients, then 10 object of HttpClient is created using IHttpClientFactory. How can we configure a single instance of HttpClient throughout whole application?
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
Well if you want to 10 _DIFFERENT_ named clients, you have no other choice
@pitthp
@pitthp 3 ай бұрын
What is good configuration for PooledConnectionLifeTime for Integration test project, that have a hundred test with API calls?
@MilanJovanovicTech
@MilanJovanovicTech 3 ай бұрын
How long does it take for your test suite execute?
@pigrebanto
@pigrebanto 3 ай бұрын
ok but what if the token expires and you need to renew it / pass-in it again? to me it seems that with Factory approach you configure it statically at application startup phase.
@MilanJovanovicTech
@MilanJovanovicTech 3 ай бұрын
Use a delegating handler
@codingbloke
@codingbloke 11 ай бұрын
Typed clients has too many gotcha's. In addition to the messy stuff you added at the end, what if you have multiple services that require the same HttpClient configuration? I just used named configurations and only inject the factory, simples.
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
You'd configure the services separately
@codingbloke
@codingbloke 11 ай бұрын
@@MilanJovanovicTech Indeed but then what you would have is all that malarkey to provide a specific configuration of a HttpClient which is only ever used by a single type and that type's only job is to wrap a specific configuration of HttpClient. In that case again you might as well have that service type do all that work. It would take the factory and what other config services it needed, and have a private method that returns a configured HttpClient
@palpie
@palpie 11 ай бұрын
You should show the strongly typed version using an interface instead.
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
You don't need interfaces for everything 🤷‍♂️
@semen083
@semen083 11 ай бұрын
It is need to add "using" for httpClient, received from IhttpClientFactory?
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
No need, it'll be garbage collected
@bahmansani3408
@bahmansani3408 11 ай бұрын
why can not find video about creating read models eventualy with eventual consistency?
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
It's a recent video, look for Materialized views
@lucid111lucid
@lucid111lucid 4 ай бұрын
My use case is a DLL which will be used with a winforms program. I expect that my DLL will be called periodically (hourly) and occasionally for a short burst of http activity. What video do you have that might help me choose the best implementation method? /Rob
@MilanJovanovicTech
@MilanJovanovicTech 4 ай бұрын
"short burst of http activity" - it doesn't look like you can do much harm whichever implementation you opt for. You could create a static HttpClient in the DLL and reuse it.
@nanvlad
@nanvlad 11 ай бұрын
What if I just call AddHttpClient() and inject HttpClient into services contstructors? Do they share the same instance or every service gets its own copy?
@TheMichaelos
@TheMichaelos 11 ай бұрын
I wanted to ask the same question! @MilanJovanovicTech I would really appreciate if you could elaborate on differences between factory injection and direct client injection 🙏
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
In theory, it shouldn't work - because no HttpClient would be wired up for that service
@juke-duke
@juke-duke 11 ай бұрын
What if you make the typed client a static class with a static HttpClient?
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
That works cool, since clients should be long-lived (at least the underlying message handler)
@adriancamposteixeira5483
@adriancamposteixeira5483 11 ай бұрын
why not the "using" or "dispose"?
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
Not needed
@user-tk2jy8xr8b
@user-tk2jy8xr8b 11 ай бұрын
It's a pity that AddHttpClient forces you to use service locator pattern
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
You win some, you lose some
@zfold4702
@zfold4702 11 ай бұрын
Now extend this for clients that need to send Jwt Token in headers with refresh token capability
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
Will do, that requires Delegating Handlers
@thecodeman_
@thecodeman_ 11 ай бұрын
Admit that you saw my post a few minutes ago, and in 20 minutes you recorded a 12-minute video, edited and uploaded it. Just admit it, I'll forgive you..
@zfold4702
@zfold4702 11 ай бұрын
Where is your post?
@MilanJovanovicTech
@MilanJovanovicTech 11 ай бұрын
Yes!
@Cesar-qi2jb
@Cesar-qi2jb 8 ай бұрын
If it was true, nothing wrong with this.
@PauloMorgado
@PauloMorgado 8 ай бұрын
You forgot to dispose the clients.
@MilanJovanovicTech
@MilanJovanovicTech 8 ай бұрын
You would only need to do it in the first example
Middleware Pattern For HttpClient With Delegating Handlers
17:07
Milan Jovanović
Рет қаралды 13 М.
Stop using the HttpClient the wrong way in .NET
10:14
Nick Chapsas
Рет қаралды 183 М.
В ДЕТСТВЕ СТРОИШЬ ДОМ ПОД СТОЛОМ
00:17
SIDELNIKOVVV
Рет қаралды 3,5 МЛН
The Beginner's Guide to Clean Architecture
13:19
Milan Jovanović
Рет қаралды 16 М.
Артём Квашнин «REST API клиенты для C#»
47:40
Swagger is Going Away in .NET 9!
10:48
Nick Chapsas
Рет қаралды 83 М.
Fix Your Controllers By Refactoring To Minimal APIs
14:56
Milan Jovanović
Рет қаралды 32 М.
Using HttpClient in .NET Core to Connect to APIs in C#
45:03
IAmTimCorey
Рет қаралды 186 М.
The Only .NET Scheduler You Should Be Using!
16:38
Nick Chapsas
Рет қаралды 44 М.
The Best Way to Add Health Checks in Any .NET App
12:31
Nick Chapsas
Рет қаралды 86 М.
iPhone 15 Unboxing Paper diy
0:57
Cute Fay
Рет қаралды 3 МЛН
iPhone 12 socket cleaning #fixit
0:30
Tamar DB (mt)
Рет қаралды 28 МЛН
cool watercooled mobile phone radiator #tech #cooler #ytfeed
0:14
Stark Edition
Рет қаралды 8 МЛН
Эффект Карбонаро и бумажный телефон
1:01
История одного вокалиста
Рет қаралды 2,8 МЛН