Web Hack Wednesday

Creating 404 middleware in ASP.NET core

Rate this post
(Video Transcript)
Hello and welcome to Web Hack Wednesday. I’m Martin Beeby.

>> And I’m Martin Kearn.

>> And today we are going to be speaking about a middleware. We already discussed middleware once but we’re gonna be looking at you, what’s wrong?

>> Middleware?

>> Yes.

>> Right, sorry. We got a problem cuz in the production meeting that we have earlier on when you mention middle wear, I thought you said leisure wear.

>> Right.

>> I thought it was a bit odd.

>> It is. Yeah.

>> But I presumed from that that we were going on holiday of some sort. So I’ve arranged for us to go on holiday to here.

>> Deal. Beautiful still waters there, Mike. Look at how still.

>> Then I was thinking, leisure wear was quite vague. So I bought us a little present each. What we’ve got here is some inflatable airplane pillow hoodies. So what happens is we put this on like this And not only are you wearing a nice comfortable hoodie to keep your head and ears warm, but you’ve got like a pillow that you can just sleep on there on the plane.

>> It’s beautiful. It’s actually branded. Look.

>> They are. They are branded. Yeah.

>> Microsoft. Microsoft Imagine. Indeed, we can only imagine the comfort that could be achieved through something like this, so.

>> Can you imagine the meeting where they agreed to create this?

>> Let’s go and release these, right?

>> I mean, I could see this being quite useful on a plane.

>> Yeah, on a plane. If we were going on a holiday, they would be very good. But without going on holiday, are we? We got middleware, you didn’t mean leisure wear.

>> Yes. [LAUGH] So-

>> Talk about asp.net.

>> Yeah, so with this now

>> Well they’re not redundant. They’re still the finest pieces of swag.

>> But I’m a bit disappointed that we’re not on holiday. So I’m gonna take us back to the studio.

>> Do you know what swag stands for?

>> I do, but I’ve forgotten and it’s better that you tell me.

>> I can’t actually, I think it’s sweaters, wearables, and gifts. I didn’t know this.

>> We both found out at the same time, didn’t we.

>> Andrew Fryer in a meeting just randomly shouted out swags, yeah, swags is-

>> Wearables and gifts.

>> And I just went wow. I’ve been working as an evangelist for six years and never known that that was the name. Anyway, by the by, so let’s have a look at-

>> Middlewear.

>> Middlewear.

>> What is middlewear then?

>> Well we’ve looked at middlewear previously on Whip out Wednesdays on asp.net core. It’s concept which is known already but is new to.

>> [INAUDIBLE] you heard correctly on the basis that we have. Yeah, it’s as if these production meetings are fictional.

>> Just vehicles for humor, which obviously we don’t take this very seriously when we do have production meetings.

>> So we just miss them every time. But the middleware concept is, a request comes into your server and you need to generate a response for the user for that browser.

>> So middleware is almost like the layers or the different pieces of software, the pieces of middleware that the request goes through to construct your request.

>> Okay.

>> A response, sorry. So the request comes in and you generate a response. So you might in an application have just one piece of middleware or you might have many pieces of middleware. And they are all-

>> But which one is the middle one? The one in the middle.

>> But if there’s two.

>> That’s difficult. There’s a midway point in the middle ware.

>> There’s an out to middle ware and in to middle wear.

>> If there was less than three then the second one’s the middle. But all of the middlewear is executed in order. The order’s an important part of it. So if we want to have a look at some of this stuff. So switch over to my machine, not to a beach.

>> We’ll get back, we’ll be leaving the beach.

>> Okay, that’s a quick flight. Right, awesome, to my machine. So I’m gonna go and create a file new ASP.NET Core application. I’m just choosing the standard web application, the start up template almost.

>> Okay. Well a 32.


>> And we are going in and When it starts. Taking its time. There we go.

>> Okay, program.cs, this is the entry point of the application. It’s just a void main in aspnet.core. So like any console aspnet application. Then it bootstraps a webhost builder, and it goes into this thing called start up. You start up for our start up. So we go to startup.cs, this is our entry point for our application. This is where we set up our configuration from our JSON files in this instance. We have some services that we configure. In our application we’re using NBC. So this is .appnbc. And finally we have this bit called Configure which is where we set up our middleware. Now there’s lots of middleware and surplus logic in here which I’m going to remove. I’m gonna leave just two pieces of middleware. App.use static files which generally looks its, the static files on disk, so images CSS files. And then app.UseMvc which is the MVC middleware which handles the controllers and all of those things and the views and bits and pieces. Now I’m gonna paste in a new piece of middleware.

>> Okay.

>> And all this is gonna do is add a response to headers and then it’s gonna invoke the next piece of middleware. So this is, it will not change the way the application worked at all. But if we looked at the actual response now, we’d have a header there, which would say author Martin Beeby on it.

>> Very good.

>> Yeah it’s great.

>> So providing you are the actual author and you haven’t stolen the code.

>> So these run in order. This is a piece of middleware. You can write it like this, inline in the configure thing. Probably not the best thing to do.

>> Okay.

>> The way that we would want to do this is we would add our own piece of middleware. And this might be in a library, in a new git file, but we’re gonna just add it as a C# file in the project.

>> Okay.

>> So right-click WebApplication32 click Add, New Item. We’re gonna select, I think it’s called Middle, MVC, yeah. Middleware Class, yeah. We’re gonna call it Middleware404.

>> Good. Good name.

>> Yeah. And this creates a little file which has a number of an interface in there. Portionally we’re gonna concern ourself was this Invoke Method. I’m just gonna add an if statement. If the httpContext.Response.StatusCode == 404, await, just gonna convert that to an async function. await httpContext.Response.WriteAsync and I’m gonna write something out so if the, if the status code is 404, I’m going to write I CAN’T FIND THE FILE.

>> Seems quite angry that upper case, doesn’t it..

>> [LAUGH] Upper yeah, It’s just going to do a very basic.

>> I can’t find the file.

>> [LAUGH]

>> It’s an async method so I’m going to return, not return but await the next piece of middleware. So I put a break in there and then I just go into my pipeline and configure, and say, app. And then I can use that piece of middleware by saying UseMiddleware404,

>> Right, cool.

>> And then if we run this up it will hit that break point that we’ve set up in the UseMiddleware404.

>> This is currently, is the middle bit of middlewear].

>> [LAUGH] The state’s code is 200 here, not 404. And if we play that through, it’s just gonna open up the website normally. Even though we might have put in an error or a 404 message, it’s not actually gonna show us anything. Now, just go over to PowerPoint, and let me get the pen out here. Now, the reason for this is if we have, we’ve got one piece of middleware which is our static files. And then we’ve got our 404 piece of middlewear.

>> The middle bit.

>> The middle bit. And then we’ve got MPC middleware. My logic at the moment is asking for a 404 error here. Because you see the middleware is doing its logic. And then it’s doing its logic here. And then it’s calling the next function, which calls the next piece of middleware. And then it executes the piece of logic which is the bit where I’m looking for a 404 error. And then executes the next logic. Now the reason why it’s not doing anything at the moment is because the status code is always gonna be 200 because none of these pieces of middleware actually throw a 404.

>> Right.

>> MVC this does or potentially can set the response.

>> [CROSSTALK] Response of the rates.

>> Yeah, so it knows if a root is not actually served or if it’s the incorrect root, it will, that middleware will actually send a 4, can I just write on, yeah, 404. Which is what we’d expect. So this is gonna call, this middleware, my new piece of middleware’s gonna call next. And then it’s gonna call into this piece of middleware, which is our ASP stuff, which is the controller and stuff. And then it’s gonna return back into my existing middleware but after that next. That call to next.

>> So there’s a begin, there’s an in and an out for each piece of…

>> Yeah, if you like yeah. So you’re effectively, no it doesn’t have to have that. If you just want an in then the last thing that you call is next.

>> Right.

>> If you just wanna be out, then you add all the logic after the next.

>> So you have call next at some point, it’s just where in the flow.

>> Yeah, you don’t have to call next but what’ll happen is that if you don’t call next then anything below,

>> Just fall through.

>> It won’t actually fall through, it’ll never call it. It will never call the next piece of middleware. You have to have a next to call the next piece of middleware in the chain.

>> Got it.

>> So you have this weird sort of, this going down the pipe and then all the way back up, which is an important thing.

>> So really, the true middle is here.

>> [LAUGH]

>> That’s the middle of the middleware.

>> Yeah, that is the middle of the middleware.

>> Good. It’s going straight in my head now. I understand it now.

>> And I need to move my logic from before the next to after the next, if that makes sense. So I’m just gonna move that. So in here, we’re gonna say that if h contact states, cuz I’m gonna move that after the next. All that means after the next, is inside the invoke method, after this thing which we call underscore next. And now it’s gonna happen, if you like, after, after it’s already been passed through to the MVC.

>> Yeah, okay.

>> I’m actually realized that my diagram has three elements and actually my middleware, I’ve got four there.

>> Well let’s not worry too much about that.

>> So now if I pass in a route which doesn’t work, it will, I can’t find the file it’s just gonna write that asynchronously. Yeah that’s fine, I’ve written some text async.

>> Yup.

>> It could serve up a HTML page, it could do whatever but what I discovered was once I discovered that thing about middleware and I discovered about this thing, I realised that actually, it’s not a good idea to write your own H404 thing. There actually is something in the framework which handles this very problem. And I’m just gonna add in here code UseStatusCodePagesWithReExecute. And this will actually handle all status codes, not just 404. And what I can do is, it will reexecute the request, starting from the start again. But it will go down this new url. So if a 404 is detected its gonna go down to errors, index and then it will pass over the status code error message. Anything gotten in the 200. So what this means now is I can in my MVC application, if I can add a controller called errors. MVC class controller, I’ll just call that an errors controller. And put a one. Add. And then I’ll just add a view. Pointing to other new folder, errors, and then just an index CSHTML file.

And in that file I’ll just, in regular capitals [LAUGH]. I’ll just-

>> He’s still angry.

>> Okay, this is now an MVC view. Save that, and then run that. And now if we get a 404 error, rather than rather than just responsing with a async right, it’s going to reexecute the MVC pipeline.

>> Okay.

>> The middleware pipeline, as if it were a new request, but now it’s gonna go down this new URL. The cool thing about that, it maintains the URL which it previously existed so you still see it was FDFDSS thing. Still there. But that’s it. That’s fundamentally how you write a 404 piece of middle ware or how you create middle ware or how middle wear works in SP.net.

>> So the flow of execution is very important.

>> It’s important to know what next means and how you can execute logic before and after it and how that will execute in this kind of the flow of your middleware. And it’s important to know if you’re trying to create a logger, you need to that at the start, but then actually you might wanna log the information throughout all the request pipeline and then print to screen or whatever, at the very end. So you need, it’s important to know how it all works and how it all flows. But that is middleware in SP, cool?

>> Brilliant. And we’ll still not going on holiday.

>> And we’re not going on holiday, but nevermind.

>> Well. At least we’ve learned some things.

>> [LAUGH] Thank you very much for joining us for another addition of Web Hack Wednesdays. We’ll see you next Wednesday for more web madness.


Read the video

In this episode Martin and Martin look at how you create custom middleware and use it to give users 404 status code error pages.

Comments to Creating 404 middleware in ASP.NET core

  • "One may only imagine the comfort that is achievable"

    AdmiralLanDi March 24, 2017 7:46 pm Reply

Leave a Comment

Your email address will not be published. Required fields are marked *

1Code.Blog - Your #1 Code Blog