HTTPS Redirect in ASP.NET Core using OWIN Middleware

0 Flares Twitter 0 Facebook 0 StumbleUpon 0 Google+ 0 LinkedIn 0 0 Flares ×

HTTPS Redirect

I’ve lost count of the number of times I’ve needed a simple HTTPS redirect in a web application – every project I seem to work on needs it sooner or later (usually sooner). Whenever it happens I always end up writing it in a slightly different way – so I thought I’d just do a short post this week on it.

More specifically I wanted to write a very simple piece of OWIN middleware for ASP.NET Core that redirects all requests to their HTTPS counterpart.

tl;dr – you can find the middleware class in the HttpsRedirectMiddleware gist here

The Goal

This really isn’t anything complicated, but I think pretty useful. The goal is top create a simple piece of middleware for plugging into the ASP.NET Core startup to redirect every request to HTTPS. I should preface this by saying you don’t have to implement the full middelware component to achieve this simple task, but the end result is much neater, and makes your code more readable.

Its really just 3 simple steps:

Step 1 – Create the Middleware

So first its the middleware class:

The simple explanation is that once plugged into the OWIN pipeline, all requests will flush through the Invpoke method. If the request is not already HTTPS, it gets redirected to the HTTPS equivalent. If the request is already HTTPS, the request is just allowed to flow down the pipeline. Easy!

Step 2 – Create the Extension Method

The extension method is what makes everything in your startup class look so neat and tidy:

For simplicity I just put this in the same file and namespace as the middleware component.

All this is really doing is plugging the middleware component into the pipeline, and wrapping it in a nice easy to call extension method.

Step 3 – Use it in your Startup

So the last step is to use the component in your ASP.NET Startup class.

Generally I like to plug it in as early as possible, within the Configure method, and only have it trigger in non-development environments. I sometimes have a setting to turn it on or off but I thought in this example using env.IsDevelopment() was the simplest approach

Thats it

So its a really simple snippet today, but one hopefully you’ve found useful! I didn’t think it really warranted a nuget packaqe and proper project, buit if its something people would be interested in then let me know and I’ll get it up and running.

You can find the HttpsRedirectMiddleware gist here

Also, please let me know if you have any improvements on what I’ve done here.

  • Игорь Валиковский

    Very easy and clear! Great solution! Thanks!

The Essential App Marketing Kit
Subscribe To My Newsletter To Get an Entire Chapter From The Book for FREE
Never display this again
0 Flares Twitter 0 Facebook 0 StumbleUpon 0 Google+ 0 LinkedIn 0 0 Flares ×