Create a gist now

Instantly share code, notes, and snippets.

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));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment