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(); } 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(); } } }