Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

tpeczek commented Apr 14, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.