Тёмный

asp.net core - HttpClient & IHttpClientFactory Tutorial & Tips (+ System.Net.Http.Json) 

Raw Coding
Подписаться 72 тыс.
Просмотров 36 тыс.
50% 1

Tutorial about how to use the HttpClient in an asp.net core app in various way. Going as far as setting up a simple micro services scenario as well as showing the System.Net.Http.Json package.
Patreon 🤝 / raw_coding
Courses 📚 learning.raw-coding.dev
Shop 🛒 shop.raw-coding.dev
Discord 💬 / discord
Twitter 📣 / anton_t0shik
Twitch 🎥 / raw_coding
👉 Try Rider
www.jetbrains.com/store/redeem/
RD5K9-4TXXW-KMV3G-NYWSF-3ZSTP
System.Net.Http.Json: www.nuget.org/packages/System...
My video about Middleware: • In/Out Middleware Expl...
Source: github.com/raw-coding-youtube...
-- Documentation --
How To Use Docs
docs.microsoft.com/en-us/aspn...
About the problem with HttpClient
docs.microsoft.com/en-us/dotn...
HttpMessageHandler (the thing that our middleware plugs into)
docs.microsoft.com/en-us/dotn...
#csharp #aspnetcore

Опубликовано:

 

25 июл 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 91   
@mahmoudalaskalany
@mahmoudalaskalany 4 года назад
glade to be patreon on raw coding am waiting for the c# course :)
@RawCoding
@RawCoding 4 года назад
Cheers :D
@jorgellanque7704
@jorgellanque7704 8 месяцев назад
I love your enthusiasm
@tmaxnoda4008
@tmaxnoda4008 4 года назад
Guy you are a gem and codegician.. You make coding life more easier bro. Much love..
@RawCoding
@RawCoding 4 года назад
Cheers ma dud ))
@tmaxnoda4008
@tmaxnoda4008 4 года назад
I will love it if you can create content on signalr with .net core 3.0
@RawCoding
@RawCoding 4 года назад
I’ll take a look in to it :)
@marlonfernandez9546
@marlonfernandez9546 3 года назад
Thank you for the video. It is good explained and complete. It help me a lot on understanding how work with HttpClient.
@RawCoding
@RawCoding 3 года назад
thank you for watching )
@mattaku9430
@mattaku9430 Год назад
This is a really cool guide
@gabrielt6529
@gabrielt6529 3 года назад
Great video!!!
@RawCoding
@RawCoding 3 года назад
Cheers
@flaviusioan69
@flaviusioan69 4 года назад
Very easy and clear explanation...tnx
@RawCoding
@RawCoding 4 года назад
Thanks for watching :)
@badrulhussain5545
@badrulhussain5545 3 года назад
Man, I love all your videos. Do you have a full tutorial that covers all of API .net core?
@RawCoding
@RawCoding 3 года назад
Cheers and no
@saurabhchauhan232
@saurabhchauhan232 4 года назад
Thank you for the great video
@RawCoding
@RawCoding 4 года назад
Thanks for watching:)
@subinsadanandan5145
@subinsadanandan5145 3 года назад
Nicely explained
@RawCoding
@RawCoding 3 года назад
Thank you
@kiranr1562
@kiranr1562 Год назад
Everything looks clean and exactly what I am looking. Question: How can we pass the Token to the API Client from WEB-Application (MVC Project) on Login Success?
@oleksandrdidenko1872
@oleksandrdidenko1872 3 года назад
Amazing video and amazing channel as well! My suggestion is to create the same video for WCF factory. Thanks a lot!
@RawCoding
@RawCoding 3 года назад
Cheers, I’ll take a look at what that is
@ivanvincent7534
@ivanvincent7534 3 года назад
Great videos.. What interests me most is your mental model and how it allows you to code with such ease and flow. What would say are the key learnings to develop with the fluency you demonstrate? Cheers.
@RawCoding
@RawCoding 3 года назад
Learn Clojure
@ivanvincent7534
@ivanvincent7534 3 года назад
@@RawCoding Will do. Thanks for that input.
@oguz40
@oguz40 4 года назад
Thank you for this great video, I've spent days finding solutions to some of the issues you mentioned in the video. I wish you had recorded this a few months earlier :) and for the viewers, please follow everything he says in the video to avoid having headaches :) altough, there is something I still can't find a solution for, which is to change the proxy details on every call. as you know there is no way to change the proxy details once you created the httpclient, and I can't create a new httpclient instance due to issues you mentioned in the video. so I'm not sure if there is a solution but I'd really appricate if you have any solution for this, nevertheless it's a great video
@RawCoding
@RawCoding 4 года назад
Thank you, you make a class that inherits from you current custom httpclient so you preserve all the defenitions, add the proxy settings and then inject your httpclient or custom one. Use the factory to create your httpclient, if you inject it it’ll be re created automatically Another approach is to set the proxy on the machine it self if you are using Linux box it’s not too hard.
@konstantinadureva6053
@konstantinadureva6053 3 года назад
Thank you, this was the first material I found on HTTP communication between APIs. I follow your simplest example, with a named HTTP client. I run both APIs via IIS and on the consumer set as a base address of the HTTP client the IIS-generated URL of the source API. Then I call my consumer controller method where on the client I call GetFromJsonAsync and as a parameter specify the path from the respective source API method I am interested in. This returns Not Found. Any idea what I'm doing wrong?
@RawCoding
@RawCoding 3 года назад
You’ll have to double check and try to hit the route from the address bar of the browser and try to understand what’s the difference between the httpclient and doing it manually
@mahmoudalaskalany
@mahmoudalaskalany 4 года назад
great topic as usual can you make a tutorial for using any messaging queue service in .net core like Rabbit MQ and how to use it between two services in .net core
@RawCoding
@RawCoding 4 года назад
Mmmm never used rabbit mq sorry
@user-gn7vb2yv7j
@user-gn7vb2yv7j 3 года назад
thanks a lot Top
@RawCoding
@RawCoding 3 года назад
Спасибо что посмотрел
@biyankaperera1443
@biyankaperera1443 3 года назад
First of all, this is a very good tutorial, a bit fast so had to watch several times though :). I have a question, maybe a stupid one, so apologise in advance and correct me if I am wrong. when adding a typed HTTP client to the service collection and injecting a HttpClient in the constructor, wouldn't it be doing the same things as creating a new instance of the httpclient or is it still using the pool to create clients? Cheers
@RawCoding
@RawCoding 3 года назад
Eeeh if I remember correctly the Messenger handler or whatever that you can pass in to the httpclient constructor, the client factory creates new httpclients however correctly manages that parameter not to eat up ports on your PC
@biyankaperera1443
@biyankaperera1443 3 года назад
@@RawCoding Thank you so much for your prompt reply, I understand now. Sorry, I am still trying to get my head around DI stuff. Great stuff Raw Coding... very good learning resources and well explained. I refactored my HttpClient code after watching this tutorial.... again great stuff. Keep up the good work mate.
@solomonmckay3126
@solomonmckay3126 Год назад
How would one go about replacing the HttpClient's base address after the service has been registered? Say this was for a desktop application and the user wanted to update the address that the application interfaces with
@mitchell4217
@mitchell4217 4 года назад
Where is the best place to put your method that calls an existing REST endpoint? Is it a controller? A service layer? A separate layer? I know you still have to register it on the startup, but what's the best place architecturally?
@RawCoding
@RawCoding 4 года назад
Wherever it makes sense
@coppernecos257
@coppernecos257 4 года назад
Thank You Bro For Your Efforts ... I Want To Ask You Question out the scope of the lecture ... which Best Processors For The better performance experience For Programming ====> (Old Xeon) or (Ryzen)?
@RawCoding
@RawCoding 4 года назад
Very vague so no clue
@coppernecos257
@coppernecos257 4 года назад
@@RawCoding so if you don't mind what is the name of your processor?
@RawCoding
@RawCoding 4 года назад
I don’t know :) intel something 4 cores 8 threads 2.* ghz maybe 6 to 10 mb cache
@coppernecos257
@coppernecos257 4 года назад
@@RawCoding ok, thank you bro for answer :)
@qixinliu758
@qixinliu758 4 месяца назад
Hi, I love your tutorial and video. I have a question tho, HttpClientFactory does not have the option to add parameters for the request, while HttpClient has that option, correct? I am having a problem with my target API; it takes two parameters, and I need to figure out how to add two parameters to my request. Would you mind explaining how I make that call with HttpClientFactory, please? My target API signature looks like "public string Authentication(string UN, string AP)"
@nove1398
@nove1398 3 года назад
In the case of blazor client side does the http only cookies get sent with each request after they are created by the server?
@RawCoding
@RawCoding 3 года назад
No idea :D
@nove1398
@nove1398 3 года назад
@@RawCoding or even does http client handle this issue?
@RawCoding
@RawCoding 3 года назад
I don’t know in case of blazor
@nove1398
@nove1398 3 года назад
@@RawCoding got ya, more research then
@priestley64
@priestley64 2 года назад
14:02 - Why should it never change? What if I have a derived client with more specific requirements? If I want a base client which defines a base URL, but then I inherit it to define actions on a particular resource in that service, then I will want to adjust the BaseAddress to add the path part to the URI. Or should we never inherit from typed HttpClients because of the socket exhaustion thing? I can't find a good example on how to write clean, resource specific consumers.
@RawCoding
@RawCoding 2 года назад
Yes I’d say never extend the HttpClient class. Always inject it, if you have MyServiceClient where the original instance is injected, you can have properties that take the instance and create new classes like MyServiceCarsClient so you do this: myServiceClient.Cars.List()
@priestley64
@priestley64 2 года назад
@@RawCoding yes! That exactly what I'm trying to accomplish. Resource context as a property that can be used in a generic repository class.
@RawCoding
@RawCoding 2 года назад
Do you need help implementing it or you good?
@priestley64
@priestley64 2 года назад
@@RawCoding I'm going to attempt it today, but definitely I would not turn down help.
@RawCoding
@RawCoding 2 года назад
Feel free to ask on discord a bit easier to share code there
@brunogiovagnoli3022
@brunogiovagnoli3022 4 года назад
keep doing great, I will glad to help you with money if you need. Patreon maybe? you're awesome
@RawCoding
@RawCoding 4 года назад
Yea patreon and donation links in description:)
@brunogiovagnoli3022
@brunogiovagnoli3022 4 года назад
@@RawCoding done!
@RawCoding
@RawCoding 4 года назад
Cheers Bruno :D
@jhbonarius
@jhbonarius 3 года назад
is there something like this (required?) for WebClient? I need the DownloadFile method.
@RawCoding
@RawCoding 3 года назад
Sorry not quite sure what you’re asking for.
@jhbonarius
@jhbonarius 3 года назад
@@RawCoding Sorry, I'll try to explain. I understand from your video (2:00) that you shouldn't use "new HttpClient" (because it uses up DNS port/handler) and should use a APS.net HttpClient service. Now in my project I'm not using a HttpClient, but a WebClient for http access, because I want to download files from web sites, and HttpClient doesn't have the method DownloadFile, which WebClient has. So I was wandering if "new WebClient" has the same issues as "new HttpClient". I haven't found a ".AddWebClient" servicebuilder in some "WebClientFactoryServiceCollectionExtensions".
@RawCoding
@RawCoding 3 года назад
Seems like there are quite a few examples on downloading files using the http client on the internet. As for the web client, I’ve never used it so can’t comment.
@user-bd3ij4op5k
@user-bd3ij4op5k 4 года назад
А почем асинхроный метод ты выполняешь как синхроный ? Просто бросилось в глаза, в самом начале видео в методе Bad GetStringAsync()
@RawCoding
@RawCoding 4 года назад
We return the task, we don't need to create a state machine and await on this call. public Task Bad() => client.GetStringAsync($"/homes/{Guid.NewGuid()}"); However down the execution chain it will be awaited by the MVC pipeline. I reccomend to watch my videos on async/await/task
@Telee_Pawt
@Telee_Pawt 2 года назад
What font is that in VS?
@RawCoding
@RawCoding 2 года назад
JetBrains mono
@onemorestory1
@onemorestory1 4 года назад
Can you teach us Web Api, Node, react ?
@RawCoding
@RawCoding 4 года назад
There will be a video up tomorrow about web api's in asp.net core and much more
@onemorestory1
@onemorestory1 4 года назад
@@RawCoding Yayyy !!! Thank you
@thegaribovv
@thegaribovv Год назад
Thanks for tutorial, but it think it will be so good if you spent much time on problems, not directly jumping into implementation.
@masterkodjane5772
@masterkodjane5772 3 года назад
I would like to use HttpClient on Ubuntu server , but that's not working. ( windows only )
@RawCoding
@RawCoding 3 года назад
HttpClient works on Ubuntu as well as other distorts and Mac
@masterkodjane5772
@masterkodjane5772 3 года назад
@@RawCoding when i'm implemented , i received this error : "WinHttpHandler is only supported on .NET Framework and .NET Core runtimes on Windows. It is not supported for Windows Store Applications (UWP) or Unix platforms." my code : public JsonResult PostPaid([FromBody] object ob) { String rep = ""; User d = JsonConvert.DeserializeObject(ob.ToString()); try { var vm = new { username = d.Login, password = d.Pwd }; { WinHttpHandler httpHandler = new WinHttpHandler(); httpHandler.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls; HttpClient client = new HttpClient(httpHandler); client.DefaultRequestHeaders.Add("Accept", "application/json"); var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(d.MyUrl), Content = new StringContent(JsonConvert.SerializeObject(vm)) }; httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage result = client.SendAsync(httpRequestMessage).Result; rep = result.Content.ReadAsStringAsync().Result; } } catch (Exception ex) { return Json(ex.Message); } return Json(rep); }
@RawCoding
@RawCoding 3 года назад
So say WinHttpHandler is not supported on Ubuntu, not http client
@masterkodjane5772
@masterkodjane5772 3 года назад
@@RawCoding sorry for the ambiguity, even if I use the constructor without parameters, (HttpClient client = new HttpClient ();) I still have this error: "One or more errors occurred. (A task was canceled.)". Yet on windows it's perfect . Thank you
@RawCoding
@RawCoding 3 года назад
Yeah that’s because you are calling .Result you are not letting the exception be thrown - use async await instead
@alirezanet
@alirezanet 3 года назад
why you are not using vscode? visual studio is trash (except the code compiler). try vscode + vim setup
@RawCoding
@RawCoding 3 года назад
I use visual studio because it is more accessible. But vs code isn’t that good, I use Rider in my day to day
@tmp1k
@tmp1k 2 года назад
what might be going on with the cleanup process if i'm seeing debug logs such as this Microsoft.Extensions.Http.DefaultHttpClientFactory: Debug: Starting HttpMessageHandler cleanup cycle with 6 items Microsoft.Extensions.Http.DefaultHttpClientFactory: Debug: Ending HttpMessageHandler cleanup cycle after 0.0024ms - processed: 0 items - remaining: 6 items and the remaining count just keeps increasing i'm currently using the named http client approach, setting up headers, base url and retry policy in startup, injecting IHttpClientFactory into a typed client to build the urls and make the requests and then injecting the typed client, in this case, into a BackgroundService that polls and api every minute in testing. Each minute the service invokes a Get method on the typed client and typed client call factory.Create("namedClientName") and uses the result client to make the async get call. As I leave the service running and observe the logs, it appears as though the HttpMessageHandler are expiring and not getting cleaned up. I also tried injecting a IServiceProvider into the background service and having the service request a Typed client instance from the service provider, thinking that the get service pipeline would allow the http client factory to inject a fresh http client into the tpyed client. In this case the background service is created once, initially i was just registering as a typed client in startup and injecting that everywhere but then realized since the background service start up once and just polls, it just holds onto the same http client for the lifespan of the process. in that case remaining items stays at 1. In trying to improve that, it seems I made it worse?
Далее