Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple OWIN middleware for doing an HTTPs redirect for all requests
// Ref: http://www.codenutz.com/https-redirect-asp-net-core-using-owin-middleware/
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Builder;
namespace SomeNamespace
{
public class HttpsRedirectMiddleware {
private RequestDelegate _next;
public HttpsRedirectMiddleware(RequestDelegate next) {
_next = next;
}
public async Task Invoke(HttpContext context){
var protoHeader = context.Request.Headers["X-Forwarded-Proto"].ToString();
if(context.Request.IsHttps || protoHeader.ToLower().Equals("https"))
await _next.Invoke(context);
}
else
{
context.Response.Redirect($"https://{context.Request.Host}{context.Request.Path}");
}
}
}
public static class HttpsRedirectMiddlewareExtensions
{
public static IApplicationBuilder UseHttpsRedirect(this IApplicationBuilder builder)
{
return builder.UseMiddleware<HttpsRedirectMiddleware>();
}
}
}
@Lutando

This comment has been minimized.

Lutando commented Aug 19, 2016

line 19 you're missing open parentheses at the end :)

@jtheisen

This comment has been minimized.

jtheisen commented Mar 26, 2018

This isn't OWIN, it's ASP.NET Core.

@BojoDimov

This comment has been minimized.

BojoDimov commented Jul 23, 2018

With a little change works like a charm. Thank you!

@atom1cx

This comment has been minimized.

atom1cx commented Oct 12, 2018

The code for OWIN is look like this:

    public async override Task Invoke(IOwinContext context)
    {
        var protoHeader = context.Request.Headers["X-Forwarded-Proto"]?.ToString();
        if (context.Request.IsSecure || (protoHeader != null && protoHeader.ToLower().Equals("https")))
        {
            await Next.Invoke(context);
        }
        else
        {
            context.Response.StatusCode = 302;
            context.Response.Redirect($"https://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}");
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment