Skip to content

Instantly share code, notes, and snippets.

@tpeczek
Created December 7, 2017 20:18
Show Gist options
  • Save tpeczek/58fdae48b8ed46a5efa4d122b2c11616 to your computer and use it in GitHub Desktop.
Save tpeczek/58fdae48b8ed46a5efa4d122b2c11616 to your computer and use it in GitHub Desktop.
ASP.NET Core middleware for POST Tunneling support
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
namespace Demo.AspNetCore.PostTunneling.Middlewares
{
public class PostTunnelingMiddleware
{
private readonly RequestDelegate _next;
private readonly string _headerName;
private readonly HashSet<string> _allowedMethods;
public PostTunnelingMiddleware(RequestDelegate next, IOptions<PostTunnelingOptions> options)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
if (options?.Value == null)
{
throw new ArgumentNullException(nameof(options));
}
_headerName = options.Value.HeaderName;
_allowedMethods = new HashSet<string>();
if (options.Value.AllowedMethods != null)
{
foreach (string allowedMethod in options.Value.AllowedMethods)
{
_allowedMethods.Add(allowedMethod.ToUpper());
}
}
}
public Task Invoke(HttpContext context)
{
if (HttpMethods.IsPost(context.Request.Method))
{
if (context.Request.Headers.ContainsKey(_headerName))
{
string tunelledMethod = context.Request.Headers[_headerName];
if (_allowedMethods.Contains(tunelledMethod))
{
IHttpRequestFeature httpRequestFeature = context.Features.Get<IHttpRequestFeature>();
httpRequestFeature.Method = tunelledMethod;
}
}
}
return _next(context);
}
}
}
using System;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Builder;
namespace Demo.AspNetCore.PostTunneling.Middlewares
{
public static class PostTunnelingMiddlewareExtensions
{
public static IApplicationBuilder UsePostTunneling(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
return app.UseMiddleware<PostTunnelingMiddleware>();
}
public static IApplicationBuilder UsePostTunneling(this IApplicationBuilder app, PostTunnelingOptions options)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
return app.UseMiddleware<PostTunnelingMiddleware>(Options.Create(options));
}
}
}
using System.Collections.Generic;
namespace Demo.AspNetCore.PostTunneling.Middlewares
{
public class PostTunnelingOptions
{
public string HeaderName { get; set; }
public IEnumerable<string> AllowedMethods { get; set; }
}
}
@tpeczek
Copy link
Author

tpeczek commented Apr 14, 2018

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