Last active
November 24, 2020 23:22
-
-
Save mattwhetton/72d1cd532115e103600b6b6cfd5c50dc to your computer and use it in GitHub Desktop.
Simple OWIN middleware for doing an HTTPs redirect for all requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@atom1cx
did not work for me beause I use non standard http/https (10080/10043) ports and my webapp listens on a different base path "/app"
so the best thing is to se context.Request.Uri for redirection.
this is my modified version that works pretty well