The Secret HttpClient Feature You Need To Use in .NET

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everybody I'm Nick in this video I'm going to show you how you can leverage a feature that is sort of hidden in the HTTP client that many people are not using but really should it's sort of a secret feature and Microsoft is using it internally for many many things we're going to see one of them in this video but I'm also going to show you how you can use it to really do some fantastic stuff with it and there's really no limit with what you can do with this feature if you like content and you want to see more make sure you subscribe for more training check out my courses on D train.com now quick announcement before I move on we have a brand new course on dome train called getting started with domain driven design that has been one of the most requested topics for courses on Dom train and is finally here and is authored by the excellent educator and content creator Amai mm now in case you don't know Amai has his own YouTube channel Link in the description give him a sub but he's also a software engineer in Microsoft whose code Powers Technologies behind things like Microsoft Office so literally hundreds of millions of users a month use the stuff he writes he's is an expert on the topic and he actually runs training like that in Microsoft as well so you're getting the highest quality possible which is what I wanted to offer with dom train in the first place now to celebrate the launch I'd like to offer the first 500 of you a 20% discount code on the course so use code ddd2 at checkout to claim it and trust me want to say these do go quick so if you want to buy it buy it now also if you buy this getting started DDD course you will also get a special discount code when the Deep dive and advanced versions of this course are out so you can double dip in these counts all right enough with that back to the video so let me show what I have here I have a simple net 8 API over here and it's sort of a weather API but it's calling a real Weather Service I'm using the open weather map API which is a free sort of a free tier um real weather API you can use to grab the weather so what I can do here if I just quickly run this just to show you what's going on is I can go into Postman and I can say give me the weather for example for London right now and I can say send and I'm going to to get the current weather for London and if I say something like Milan then I'm going to get Milan's weather and so on and so forth the way this works is I'm registering this open Weather Service over here which is using an HTTP client Factory to create clients over here using the name client feature which we've seen this channel before and then I'm calling the API over here with this get method of the client and then getting the status code and then passing the weather and returning it and that is basically it now what I want to do is I want to add a layer of caching in here because when you're getting the weather especially in a service like this where we're paying per request how much can the weather change in a minute in London a lot but in most places it doesn't really change that often so what you can do is you can add caching for example and that's just one example of the use cases you have many many use cases for what I'm going to show you but that's just one of them now you can decide to add them on the response cash the output cash you can decorate the service but one of the things you can do is actually add it on the the client itself because the HTTP client this fella over here that eventually will make that API call to the API actually has a bit of an internal pipeline for how the request is handled so when I say get a sync what is going to happen behind the scenes and in fact we can actually see by stepping into the code over here and then into this and then into this and then into Jesus Christ as many layers over here and eventually the send a sync is you're going to see that the request isn't sent by the HTTP client itself but instead through an HTTP message invoker so that's really what's causing the request to be fired and actually this is all happening through what is called a Handler which is stored here as an HTTP message Handler now there's a default one that will F those requests but you actually have control over the pipeline so you can say before you eventually reach that final Handler that will make the real request to an API I want to do some things with that request I might want to grab the request grab the details I might want to completely Sidetrack it I might say write my own custom response or I might say send it somewhere else you have full control through this pipeline but the way we're going to call this because that's really the name used here is a delegating Handler so let me just quickly show you what I mean I'm going to go ahead and create a new class and I'm going to call that weather Handler so this will be responsible for handling the caching load IC of my HTTP handlers for my request in this case I'm going to go ahead and extend the delegating Handler and as you can see I'm not forced to override anything but you can say override and you have the send Ascend async methods the synchronous and as synchronous version effectively to send that request to the next thing in the pipeline so here what I have and if I just quickly break it down so it's easier to see uh and add an example here so the gray goes away is I have the send async method which if you remember is the thing that eventually will be called to send that request to the real API but really what's going to happen here is I have a bit of a pipeline where we're starting with nothing and then we can say go into the cast weather Handler first if you find the weather be cached then just return the weather otherwise continue in the pipeline and go ahead and make the real request to do all that I'm going to go ahead and add an inmemory cache here so I'm going to say services do add in memory cache here we go and that allows me to inject the private read only IM memory cache interface and that I can inject from The Constructor like this and I can use it so the way this would work is basically like a filter in hpet core or a middleware in hpet core so since I have access to the request itself I can say grab the query string because I need to find a way to distinguish where this request is going to and say request. request u. query and I want to pass that so I'm going to say HTTP utility over here and then pause query string and I'm going to pause that query string over here then because I want to cash each request differently for each City and each things like am I getting Celsius am I getting Fahrenheit I can say give me the query from the query string and give me the units from the query string and then build a key so I'm going to build a cache key out of the query and the units then what I want to say is try to see if I have something in the cache so I'm going to say cache. getet and I'm going to store that as a string and I'm going to use the key to see if it exists if cach is not null so if I actually have something in the cache then let's go ahead and create a new HTTP message response and to do that over here I'm going to turn this into a async method so HTTP response message I'm going to say that the request is okay because that's what under normal circumstances this API would return and I'm going to go ahead and say that the content is the string content and I'm going to pass down the cast string as the content now if you actually needed things like the header or the vision or the reason phrase or any of the other parameters you can actually set them here as well in my case in this example I don't need them so this is enough to create a fake response as if the HTTP client went ahead and it made a real request but it didn't and then for the remaining of the behavior I want to say VAR response equals await so go and send that request to the real API and then give me the content so that will be response. content. read as string async which means I can pass a cancellation token but I have to also say a wait over here and then I can say cach do set so I'm going to set that value into the cach I'm going to say key is here and then the content is the string I'm going to say time span from minutes so cach that for a minute let's go ahead and do that and then return response now this will make a lot more sense as the whole process flows I'm going to go ahead and just add a breakpoint here a break point here and then I'm going to register my Handler because I need to so services. add sculpt in this case cast weather Handler and before I run it looking at this actually this should be response not request and I should be able to go ahead and run this so what I want to hit first is the open weather map service let's go ahead and call that and as you can see we hit the breakpoint so the first thing that's going to happen is we're going to get a client and I want to show you in these clients because you can actually see all the handlers so if I go into the Handler section over here you can see lifetime tracking HTP Mage Handler the top level Handler then we go one level deeper which is the logging scope Handler and these are all aspn net core and net specific handlers that they add out of the box for us then in that you can find another inner Handler and that is our Handler the C where the Handler and then our Handler has another one the loging one and then that Handler has the real HTTP client Handler and then that one has the eventual one which is the socket HTP Handler the thing that eventually files the request through the socket and that is it so now if we just step over everything we're going to get the cash key obviously there's nothing in the cache so we're going to go and make the real call we're going to put it in the cache as you can see the content is here and then I'm just going to say fired off and then the next time we come in here what is going to happen is as you'd expect we're going to go to fire that request but because we're going to have it in the cache as you can see the thing exists we're going to return it through the cache and we're not going to make a real HTTP call nothing about our application knows about this other than the hander itself so we added Behavior without actually changing anything else other than the registration of the client it is a lovely feature to use for things like this where you want to have some minor caching logic in there or maybe you have a header you want to delegate so let's say you get a request from somewhere that has correlation ID or an XC correlation ID on the header and you want to pass that down to any subsequent request something like this can do it because you can mutate the request as it's coming in um and other things you can do obviously Microsoft is using it for logging and to track metrics and performance as well I've personally used it in the past for something like this where we don't actually go into the real service but we go to a cache now in that use case admittedly I used red because my application was distributed but something like in memory lent itself very nicely to showcase the feature but now on know from you did you know about this and have you used it in the past what's the craziest use case you have or you can think of for this feature leave a comment down below and let me know well that's all I have for you for this video thank you very much for watching and as always keep coding
Info
Channel: Nick Chapsas
Views: 60,418
Rating: undefined out of 5
Keywords: Elfocrash, elfo, coding, .netcore, dot net, core, C#, how to code, tutorial, development, software engineering, microsoft, microsoft mvp, .net core, nick chapsas, chapsas, dotnet, .net, .net 8, httpclient, delegatinghandler, httpmessagehandler, delegatinghandler c#, httpclient middleware, http client .net, http client
Id: goxI3rOMnmY
Channel Id: undefined
Length: 10min 41sec (641 seconds)
Published: Mon Aug 28 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.