Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ASP.NET Core middleware for SSL Acceleration (Offloading) support
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Options;
namespace Demo.AspNetCore.SslAcceleration.Middlewares
{
public class SslAccelerationOptions
{
public string HeaderName { get; set; }
public string HeaderValue { get; set; }
}
public class SslAccelerationMiddleware
{
private const string HTTPS_SCHEME = "https";
private readonly RequestDelegate _next;
private readonly SslAccelerationOptions _options;
public SslAccelerationMiddleware(RequestDelegate next, IOptions<SslAccelerationOptions> options)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_options = options?.Value ?? throw new ArgumentNullException(nameof(options));
}
public Task Invoke(HttpContext context)
{
if (!context.Request.IsHttps)
{
if (context.Request.Headers.ContainsKey(_options.HeaderName) && context.Request.Headers[_options.HeaderName].Equals(_options.HeaderValue))
{
IHttpRequestFeature httpRequestFeature = context.Features.Get<IHttpRequestFeature>();
httpRequestFeature.Scheme = HTTPS_SCHEME;
}
}
return _next(context);
}
}
public static class SslAccelerationMiddlewareExtensions
{
public static IApplicationBuilder UseSslAcceleration(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
return app.UseMiddleware<SslAccelerationMiddleware>();
}
public static IApplicationBuilder UseSslAcceleration(this IApplicationBuilder app, SslAccelerationOptions options)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
return app.UseMiddleware<SslAccelerationMiddleware>(Options.Create(options));
}
}
}
@tpeczek

This comment has been minimized.

Copy link
Owner Author

@tpeczek tpeczek commented Apr 14, 2018

@AnkurMadaan

This comment has been minimized.

Copy link

@AnkurMadaan AnkurMadaan commented Sep 10, 2020

What is the best place to put this middleware and do i need UseHttpsRedirection() along with this? Please suggest.

@tpeczek

This comment has been minimized.

Copy link
Owner Author

@tpeczek tpeczek commented Sep 11, 2020

@AnkurMadaan I would suggest placing this middleware as early in pipeline as possible. When it comes to UseHttpsRedirection(), it is not required, it's usage depends if you want to support both HTTP and HTTPS requests or not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment