Working With HTTP Response Headers in ASP.NET Core Middleware

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
middleware is one of the coolest asp.net core features and let's be honest it's just cool and it always had some good PR the main selling point of asp.net core middleware is that they are just pieces of code that you can execute when the request comes in but also when the response goes out unfortunately theory and practice don't always overlap and sometimes out of the blue you might get this exception so in this video I'll tell you everything you need to know about this exception why we get it and how to avoid it in the future foreign hey there and welcome to the cold drinkers Channel working with HTTP responses in asp.net core middleware is not always that straightforward and there are some common scenarios where we might actually want to do this for instance when we want to manipulate in any kind HTTP response headers but let me show you what I mean by that here we are in a blank asp.net core minimal API and let's get started by adding here a simple middleware so we'll have here app.use and in this use we'll have this async and context next and that's the basic setup for a middleware now the only thing that we'll do here is wait next and will pass the context so that's a regular asp.net core middleware and as the marketing is here we will have code execute on request and if we want to execute something after the request is executed so basically on the response when the response is on its way out you would have to kind of like do here's execute on response so here we are now very common task when we work with apis or minimal apis in asp.net core is that we need to manipulate headers and more exactly response headers and there are from my point of view here two different scenarios that we might face the first scenario is when we might need to add some response headers that will be exactly the same no matter what the request so for instance let's say that we want to have a header here that would kind of like well add a hello world so we would have something similar to this and what we do here is we just add a header that has the key application and then hello world now let me execute this and then let's move over to postman tool actually take a look so the application is up and running so let's head over to postman send a request here's the response and if we take a look at the headers we see that this is our custom header application and the name of the application is hello world and the name of the application will presumably be always the same so that's the very first scenario that we might encounter when we need to manipulate headers however there is a second scenario which is very important and that is when we dynamically need to manipulate headers based on things that happen in the response or based on contextual information that we have in the response like for instance the status code and to keep things simple here let's just imagine that we want basically to add the header to the response that contains the status code so what we would be tempted to do here is move after this away.next and just add a header that we want so what we do in this case we just add a header the key is called status code and what we do here is we just get the status code from the HTTP response and that's everything that we want to do here however if we run this application right now and if we go over and make a request we see that an exception has been thrown here and if we take a look at the exception says non-handled exception occurred while executing a request invalid operation exception the response headers cannot be modified because the response has already started now let's try to understand this exception when we think about HTTP there is some very important stuff that we need to know it's not complicated but we need to be aware of it so first off in any HTTP response we have two big components we have the headers and we have the response body the important thing to understand is that HTTP responses are usually streamed and this means in turn that actually headers are sent to the client first as a response and the body is sent afterwards and this means in turn that by the time we start to send the body the headers were actually already sent to the client and that's why we get this exception but then you would ask when does the response or the body start and the answer to this question is not that straightforward because well it could start anywhere in the request pipeline for instance there might be filters that would already create a response or the controller itself or some other internal parts of asp.net or let's start already the response so we don't know exactly which is the moment when the response or where the body starts however the situation or the context here is not that bad because asp.net core or the ATP context better set exposes us some very valuable information and ways to actually hook in our code when the response starts let's look into how this would look like there are two important things that we need to be aware about when it comes to manipulating the response and adding headers first of all let's get rid of all this stuff now the first thing that I wanted to show you is that on the context basically what we have here on the response and we have this has started and this is actually a Boolean and this of course is false if the response has not started yet so the body has not yet started to be written and of course this is something that we can use for instance to check if the response has started and or not and if we are not sure exactly when the response starts that would be the method to actually get things done and understand and when this response started however there is also another approach that we could use and not to always check if the response is starting but instead asp.net core offers us also an option basically a method to just get hooked into our callback of ours in this on starting so on the context on the response we have this on starting method that takes a funk of object and of task so we need to return a task that's why we return task dot composite task here and here in this code we can perform any header manipulation that we want and this method is actually invoked or our callback is invoked by the time when the response or the body is about to get started so this is really the last place where we can hook into this type of procedure and add the headers that we want to our response and in this case we just want to add a header and once again the status code and we get the status code from the response itself now of course obviously this method needs to be or the Callback needs to be registered before the await next otherwise we would have the exact same problem but now that we have wired everything up together and that we have used this on starting method we can run the application again and go over to postman and create a new request and this time we see that we don't have any exception and instead we have here the status code of 200 which was successfully set as we did in that specific callback that we had previously to that context on starting method and that's mostly it on how we could kind of like safely manipulate or work with response headers even if we need to define those headers dynamically based on some information that we already have in the response to this on starting method is really your best friend so since pretty cool and straightforward however there are some things that we need to be aware about the first thing is we need to be aware about is that we should never use the his own starting method to actually perform changes to the body itself the problem is that the body is streamed as well and any change any tweak that we make there could potentially lead to some inconsistencies and unexpected behavior and by the way as per the documentation from asp.net core this on starting method or the purpose of this one starting method is to give us a way to manipulate headers not the body itself another thing that is very important to understand is that obviously in each middleware you could use this on starting to register some callbacks and here the important thing is to note that all these callbacks will be executed in reverse order in which they will actually register so if you think about it it's exactly like the middleware so the first callbacks that are registered are actually the last to be executed when the response has started it's really just like middleware and I would call it a wrap if you did enjoy this video don't forget to hit the thumbs up button and like this video so that you make it easier to discover for others that might also find this interesting and if you're for the first time here don't forget to hit the Subscribe button and also the notification Bell so that you are always notified whenever something new happens on this channel and if you think that this content by might be valuable also for others don't be shy and feel free to share it in your social media with your friends at work wherever you think there might be people that would actually be interested in this content share it and I'm sure that they will be thankful to you last but not least if you have any type of question or if you want to get in touch with me don't be shy and head over to the comment section of this video and leave your comment and I would be more than happy to get in touch with you this being said thank you very much for watching and until the next time I wish you the very best
Info
Channel: Codewrinkles
Views: 2,751
Rating: undefined out of 5
Keywords: aspnetcore, asp.net core, asp.net core middleware, aspnetcore midlleware, middleware asp.net core, middleware aspnetcore, dotnetcore, dotnetcore middleware, .net core, .net core middleware, asp.net core httpcontext, httpcontext aspnetcore, asp.net core response headers, aspnetcore response headers, response headers asp.net core api, asp.net core api middleware, aspnetcore api middleware, middleware aspnetcore api, middleware asp.net core api, asp.net core tutorial
Id: pCrcg8yJk7I
Channel Id: undefined
Length: 9min 25sec (565 seconds)
Published: Thu Mar 09 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.