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

КОМЕНТАРІ • 91

  • @tmaxnoda4008
    @tmaxnoda4008 4 роки тому +4

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

    • @RawCoding
      @RawCoding  4 роки тому +1

      Cheers ma dud ))

    • @tmaxnoda4008
      @tmaxnoda4008 4 роки тому +1

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

    • @RawCoding
      @RawCoding  4 роки тому +2

      I’ll take a look in to it :)

  • @marlonfernandez9546
    @marlonfernandez9546 3 роки тому +1

    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 )

  • @jorgellanque7704
    @jorgellanque7704 8 місяців тому

    I love your enthusiasm

  • @mahmoudalaskalany
    @mahmoudalaskalany 4 роки тому +5

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

  • @mattaku9430
    @mattaku9430 Рік тому

    This is a really cool guide

  • @flaviusioan69
    @flaviusioan69 4 роки тому +1

    Very easy and clear explanation...tnx

    • @RawCoding
      @RawCoding  4 роки тому

      Thanks for watching :)

  • @gabrielt6529
    @gabrielt6529 3 роки тому +1

    Great video!!!

  • @saurabhchauhan232
    @saurabhchauhan232 4 роки тому +1

    Thank you for the great video

    • @RawCoding
      @RawCoding  4 роки тому +1

      Thanks for watching:)

  • @badrulhussain5545
    @badrulhussain5545 3 роки тому +1

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

  • @subinsadanandan5145
    @subinsadanandan5145 3 роки тому

    Nicely explained

  • @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?

  • @konstantinadureva6053
    @konstantinadureva6053 3 роки тому +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  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

  • @oleksandrdidenko1872
    @oleksandrdidenko1872 3 роки тому +1

    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 роки тому +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.

  • @mitchell4217
    @mitchell4217 4 роки тому +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?

    • @RawCoding
      @RawCoding  4 роки тому +1

      Wherever it makes sense

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

  • @user-gn7vb2yv7j
    @user-gn7vb2yv7j 3 роки тому +1

    thanks a lot Top

    • @RawCoding
      @RawCoding  3 роки тому

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

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

  • @oguz40
    @oguz40 4 роки тому +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  4 роки тому +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.

  • @biyankaperera1443
    @biyankaperera1443 3 роки тому +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  3 роки тому +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 3 роки тому +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.

  • @mahmoudalaskalany
    @mahmoudalaskalany 4 роки тому +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  4 роки тому

      Mmmm never used rabbit mq sorry

  • @nove1398
    @nove1398 3 роки тому +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  3 роки тому +1

      No idea :D

    • @nove1398
      @nove1398 3 роки тому +1

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

    • @RawCoding
      @RawCoding  3 роки тому +1

      I don’t know in case of blazor

    • @nove1398
      @nove1398 3 роки тому

      @@RawCoding got ya, more research then

  • @priestley64
    @priestley64 2 роки тому +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  2 роки тому +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 2 роки тому +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  2 роки тому

      Do you need help implementing it or you good?

    • @priestley64
      @priestley64 2 роки тому +1

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

    • @RawCoding
      @RawCoding  2 роки тому +1

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

  • @jhbonarius
    @jhbonarius 3 роки тому +1

    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 роки тому +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  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.

  • @coppernecos257
    @coppernecos257 4 роки тому +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  4 роки тому +1

      Very vague so no clue

    • @coppernecos257
      @coppernecos257 4 роки тому +1

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

    • @RawCoding
      @RawCoding  4 роки тому +1

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

  • @Telee_Pawt
    @Telee_Pawt 2 роки тому +1

    What font is that in VS?

  • @user-bd3ij4op5k
    @user-bd3ij4op5k 4 роки тому +1

    А почем асинхроный метод ты выполняешь как синхроный ? Просто бросилось в глаза, в самом начале видео в методе 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

  • @brunogiovagnoli3022
    @brunogiovagnoli3022 4 роки тому +1

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

  • @onemorestory1
    @onemorestory1 4 роки тому +2

    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

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

  • @thegaribovv
    @thegaribovv Рік тому +1

    Thanks for tutorial, but it think it will be so good if you spent much time on problems, not directly jumping into implementation.

  • @alirezanet
    @alirezanet 3 роки тому +1

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

    • @RawCoding
      @RawCoding  3 роки тому +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 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?