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

Sdílet
Vložit
  • čas přidán 2. 06. 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

Komentáře • 91

  • @jorgellanque7704
    @jorgellanque7704 Před 7 měsíci

    I love your enthusiasm

  • @mahmoudalaskalany
    @mahmoudalaskalany Před 4 lety +5

    glade to be patreon on raw coding am waiting for the c# course :)

  • @tmaxnoda4008
    @tmaxnoda4008 Před 4 lety +4

    Guy you are a gem and codegician.. You make coding life more easier bro. Much love..

    • @RawCoding
      @RawCoding  Před 4 lety +1

      Cheers ma dud ))

    • @tmaxnoda4008
      @tmaxnoda4008 Před 4 lety +1

      I will love it if you can create content on signalr with .net core 3.0

    • @RawCoding
      @RawCoding  Před 4 lety +2

      I’ll take a look in to it :)

  • @marlonfernandez9546
    @marlonfernandez9546 Před 3 lety +1

    Thank you for the video. It is good explained and complete. It help me a lot on understanding how work with HttpClient.

  • @mattaku9430
    @mattaku9430 Před rokem

    This is a really cool guide

  • @saurabhchauhan232
    @saurabhchauhan232 Před 4 lety +1

    Thank you for the great video

  • @flaviusioan69
    @flaviusioan69 Před 3 lety +1

    Very easy and clear explanation...tnx

  • @gabrielt6529
    @gabrielt6529 Před 3 lety +1

    Great video!!!

  • @badrulhussain5545
    @badrulhussain5545 Před 3 lety +1

    Man, I love all your videos. Do you have a full tutorial that covers all of API .net core?

  • @subinsadanandan5145
    @subinsadanandan5145 Před 3 lety

    Nicely explained

  • @kiranr1562
    @kiranr1562 Před rokem

    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 Před 3 lety +1

    Amazing video and amazing channel as well! My suggestion is to create the same video for WCF factory.
    Thanks a lot!

    • @RawCoding
      @RawCoding  Před 3 lety

      Cheers, I’ll take a look at what that is

  • @ivanvincent7534
    @ivanvincent7534 Před 3 lety +1

    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.

  • @oguz40
    @oguz40 Před 4 lety +6

    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  Před 4 lety +1

      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.

  • @solomonmckay3126
    @solomonmckay3126 Před rokem

    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

  • @biyankaperera1443
    @biyankaperera1443 Před 3 lety +1

    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  Před 3 lety +1

      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 Před 3 lety +1

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

  • @user-gn7vb2yv7j
    @user-gn7vb2yv7j Před 3 lety +1

    thanks a lot Top

    • @RawCoding
      @RawCoding  Před 3 lety

      Спасибо что посмотрел

  • @qixinliu758
    @qixinliu758 Před 3 měsíci

    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)"

  • @konstantinadureva6053
    @konstantinadureva6053 Před 3 lety +1

    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  Před 3 lety

      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 Před 4 lety +1

    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  Před 4 lety

      Mmmm never used rabbit mq sorry

  • @mitchell4217
    @mitchell4217 Před 3 lety +1

    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?

  • @coppernecos257
    @coppernecos257 Před 4 lety +1

    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  Před 4 lety +1

      Very vague so no clue

    • @coppernecos257
      @coppernecos257 Před 4 lety +1

      @@RawCoding so if you don't mind what is the name of your processor?

    • @RawCoding
      @RawCoding  Před 4 lety +1

      I don’t know :) intel something 4 cores 8 threads 2.* ghz maybe 6 to 10 mb cache

    • @coppernecos257
      @coppernecos257 Před 4 lety

      @@RawCoding ok, thank you bro for answer :)

  • @nove1398
    @nove1398 Před 3 lety +1

    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  Před 3 lety +1

      No idea :D

    • @nove1398
      @nove1398 Před 3 lety +1

      @@RawCoding or even does http client handle this issue?

    • @RawCoding
      @RawCoding  Před 3 lety +1

      I don’t know in case of blazor

    • @nove1398
      @nove1398 Před 3 lety

      @@RawCoding got ya, more research then

  • @priestley64
    @priestley64 Před 2 lety +1

    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  Před 2 lety +1

      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 Před 2 lety +1

      @@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  Před 2 lety

      Do you need help implementing it or you good?

    • @priestley64
      @priestley64 Před 2 lety +1

      @@RawCoding I'm going to attempt it today, but definitely I would not turn down help.

    • @RawCoding
      @RawCoding  Před 2 lety +1

      Feel free to ask on discord a bit easier to share code there

  • @brunogiovagnoli3022
    @brunogiovagnoli3022 Před 4 lety +1

    keep doing great, I will glad to help you with money if you need. Patreon maybe? you're awesome

  • @user-bd3ij4op5k
    @user-bd3ij4op5k Před 4 lety +1

    А почем асинхроный метод ты выполняешь как синхроный ? Просто бросилось в глаза, в самом начале видео в методе Bad GetStringAsync()

    • @RawCoding
      @RawCoding  Před 4 lety

      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

  • @jhbonarius
    @jhbonarius Před 3 lety +1

    is there something like this (required?) for WebClient? I need the DownloadFile method.

    • @RawCoding
      @RawCoding  Před 3 lety

      Sorry not quite sure what you’re asking for.

    • @jhbonarius
      @jhbonarius Před 3 lety +1

      @@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  Před 3 lety

      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.

  • @Telee_Pawt
    @Telee_Pawt Před 2 lety +1

    What font is that in VS?

  • @onemorestory1
    @onemorestory1 Před 4 lety +2

    Can you teach us Web Api, Node, react ?

    • @RawCoding
      @RawCoding  Před 4 lety

      There will be a video up tomorrow about web api's in asp.net core and much more

    • @onemorestory1
      @onemorestory1 Před 4 lety

      @@RawCoding Yayyy !!! Thank you

  • @thegaribovv
    @thegaribovv Před rokem +1

    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 Před 3 lety

    I would like to use HttpClient on Ubuntu server , but that's not working. ( windows only )

    • @RawCoding
      @RawCoding  Před 3 lety

      HttpClient works on Ubuntu as well as other distorts and Mac

    • @masterkodjane5772
      @masterkodjane5772 Před 3 lety

      @@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  Před 3 lety

      So say WinHttpHandler is not supported on Ubuntu, not http client

    • @masterkodjane5772
      @masterkodjane5772 Před 3 lety

      @@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  Před 3 lety

      Yeah that’s because you are calling .Result you are not letting the exception be thrown - use async await instead

  • @alirezanet
    @alirezanet Před 3 lety +1

    why you are not using vscode? visual studio is trash (except the code compiler). try vscode + vim setup

    • @RawCoding
      @RawCoding  Před 3 lety +1

      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 Před 2 lety

    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?