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

  Рет қаралды 35,856

Raw Coding

Raw Coding

4 жыл бұрын

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

Пікірлер: 91
@mahmoudalaskalany
@mahmoudalaskalany 4 жыл бұрын
glade to be patreon on raw coding am waiting for the c# course :)
@RawCoding
@RawCoding 4 жыл бұрын
Cheers :D
@jorgellanque7704
@jorgellanque7704 7 ай бұрын
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 3 жыл бұрын
Very easy and clear explanation...tnx
@RawCoding
@RawCoding 3 жыл бұрын
Thanks for watching :)
@saurabhchauhan232
@saurabhchauhan232 4 жыл бұрын
Thank you for the great video
@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
@subinsadanandan5145
@subinsadanandan5145 3 жыл бұрын
Nicely explained
@RawCoding
@RawCoding 3 жыл бұрын
Thank you
@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
@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?
@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.
@user-gn7vb2yv7j
@user-gn7vb2yv7j 3 жыл бұрын
thanks a lot Top
@RawCoding
@RawCoding 3 жыл бұрын
Спасибо что посмотрел
@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.
@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.
@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
@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
@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
@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
@qixinliu758
@qixinliu758 3 ай бұрын
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)"
@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 :)
@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
@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.
@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
@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
@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
@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.
@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
@Telee_Pawt
@Telee_Pawt 2 жыл бұрын
What font is that in VS?
@RawCoding
@RawCoding 2 жыл бұрын
JetBrains mono
@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?
ASP.NET Core Kestrel Explained
15:58
Raw Coding
Рет қаралды 11 М.
The joker's house has been invaded by a pseudo-human#joker #shorts
00:39
Untitled Joker
Рет қаралды 11 МЛН
Stupid Barry Find Mellstroy in Escape From Prison Challenge
00:29
Garri Creative
Рет қаралды 21 МЛН
.NET Framework vs .NET Core vs .NET vs .NET Standard vs C#
25:14
IAmTimCorey
Рет қаралды 541 М.
asp.net core - MediatR (CQRS) Tutorial & Tips
39:10
Raw Coding
Рет қаралды 65 М.
Semaphore Explained C#
12:24
Raw Coding
Рет қаралды 39 М.
HttpClient in Asp.Net Core Web API | HttpClient C#
27:33
Nitish Kaushik
Рет қаралды 3,6 М.
8 await async mistakes that you SHOULD avoid in .NET
21:13
Nick Chapsas
Рет қаралды 309 М.
Secure a .NET Core API with Bearer Authentication
1:06:56
Les Jackson
Рет қаралды 189 М.
How To Mock HttpClient in C# Unit Tests
11:33
Raw Coding
Рет қаралды 17 М.
What you should know about Threads in .NET
14:52
Raw Coding
Рет қаралды 7 М.