Skip to content

Instantly share code, notes, and snippets.

@ddrinka
Created January 5, 2018 14:45
Show Gist options
  • Save ddrinka/8418fef0fcc6f9455dd2c01f645560c6 to your computer and use it in GitHub Desktop.
Save ddrinka/8418fef0fcc6f9455dd2c01f645560c6 to your computer and use it in GitHub Desktop.

Revisions

  1. ddrinka created this gist Jan 5, 2018.
    52 changes: 52 additions & 0 deletions ProxyPathMiddleware.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Text;
    using System.Threading.Tasks;
    using Amazon.Lambda.APIGatewayEvents;
    using Amazon.Lambda.AspNetCoreServer;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Logging;

    namespace WebApi
    {
    public class ProxyPathMiddleware
    {
    readonly RequestDelegate _next;
    readonly ILogger _logger;

    public ProxyPathMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
    {
    _next = next;
    _logger = loggerFactory.CreateLogger<ProxyPathMiddleware>();
    }

    public Task Invoke(HttpContext context)
    {
    if (!context.Items.TryGetValue(APIGatewayProxyFunction.APIGATEWAY_REQUEST, out var apiGatewayRequestObject))
    return _next(context); //This was not an API Gateway request. Move on.

    var apiGatewayRequest = apiGatewayRequestObject as APIGatewayProxyRequest;
    if (apiGatewayRequest == null)
    throw new InvalidOperationException("An API Gateway Request was set but was an invalid type");

    if (apiGatewayRequest.PathParameters == null || !apiGatewayRequest.PathParameters.TryGetValue("proxy", out var proxyPath))
    return _next(context); //This was an API Gateway request but was not proxied. Move on.

    var newPath = WebUtility.UrlDecode("/" + proxyPath);
    _logger.LogDebug($"Rewriting request path. Original={context.Request.Path} New={newPath}");

    context.Request.Path = newPath;
    return _next(context);
    }
    }

    public static class ProxyPathMiddlewareExtensions
    {
    public static IApplicationBuilder UseProxyPath(this IApplicationBuilder builder)
    {
    return builder.UseMiddleware<ProxyPathMiddleware>();
    }
    }
    }