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.
Lambda ASP.Net Core middleware which uses only the proxy path portion of the request for routing
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>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment