asp.net core - HttpClient & IHttpClientFactory Tutorial & Tips (+ System.Net.Http.Json)
Вставка
- Опубліковано 2 чер 2020
- 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
Guy you are a gem and codegician.. You make coding life more easier bro. Much love..
Cheers ma dud ))
I will love it if you can create content on signalr with .net core 3.0
I’ll take a look in to it :)
Thank you for the video. It is good explained and complete. It help me a lot on understanding how work with HttpClient.
thank you for watching )
I love your enthusiasm
glade to be patreon on raw coding am waiting for the c# course :)
Cheers :D
This is a really cool guide
Very easy and clear explanation...tnx
Thanks for watching :)
Great video!!!
Cheers
Thank you for the great video
Thanks for watching:)
Man, I love all your videos. Do you have a full tutorial that covers all of API .net core?
Cheers and no
Nicely explained
Thank you
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?
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?
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
Amazing video and amazing channel as well! My suggestion is to create the same video for WCF factory.
Thanks a lot!
Cheers, I’ll take a look at what that is
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.
Learn Clojure
@@RawCoding Will do. Thanks for that input.
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?
Wherever it makes sense
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
thanks a lot Top
Спасибо что посмотрел
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)"
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
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.
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
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
@@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.
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
Mmmm never used rabbit mq sorry
In the case of blazor client side does the http only cookies get sent with each request after they are created by the server?
No idea :D
@@RawCoding or even does http client handle this issue?
I don’t know in case of blazor
@@RawCoding got ya, more research then
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.
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()
@@RawCoding yes! That exactly what I'm trying to accomplish. Resource context as a property that can be used in a generic repository class.
Do you need help implementing it or you good?
@@RawCoding I'm going to attempt it today, but definitely I would not turn down help.
Feel free to ask on discord a bit easier to share code there
is there something like this (required?) for WebClient? I need the DownloadFile method.
Sorry not quite sure what you’re asking for.
@@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".
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.
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)?
Very vague so no clue
@@RawCoding so if you don't mind what is the name of your processor?
I don’t know :) intel something 4 cores 8 threads 2.* ghz maybe 6 to 10 mb cache
@@RawCoding ok, thank you bro for answer :)
What font is that in VS?
JetBrains mono
А почем асинхроный метод ты выполняешь как синхроный ? Просто бросилось в глаза, в самом начале видео в методе Bad GetStringAsync()
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
keep doing great, I will glad to help you with money if you need. Patreon maybe? you're awesome
Yea patreon and donation links in description:)
@@RawCoding done!
Cheers Bruno :D
Can you teach us Web Api, Node, react ?
There will be a video up tomorrow about web api's in asp.net core and much more
@@RawCoding Yayyy !!! Thank you
I would like to use HttpClient on Ubuntu server , but that's not working. ( windows only )
HttpClient works on Ubuntu as well as other distorts and Mac
@@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);
}
So say WinHttpHandler is not supported on Ubuntu, not http client
@@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
Yeah that’s because you are calling .Result you are not letting the exception be thrown - use async await instead
Thanks for tutorial, but it think it will be so good if you spent much time on problems, not directly jumping into implementation.
why you are not using vscode? visual studio is trash (except the code compiler). try vscode + vim setup
I use visual studio because it is more accessible. But vs code isn’t that good, I use Rider in my day to day
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?