Skip to content

Instantly share code, notes, and snippets.

@avanderhoorn
Last active August 29, 2015 14:27
Show Gist options
  • Save avanderhoorn/00de3272901797060812 to your computer and use it in GitHub Desktop.
Save avanderhoorn/00de3272901797060812 to your computer and use it in GitHub Desktop.
public static class MapUseExtensions
{
public static IApplicationBuilder MapUse(this IApplicationBuilder app, PathString pathMatch, Action<IApplicationBuilder> configuration)
{
if (pathMatch.HasValue && pathMatch.Value.EndsWith("/", StringComparison.Ordinal))
{
throw new ArgumentException("The path must not end with a '/'", nameof(pathMatch));
}
// create branch
var branchBuilder = app.New();
configuration(branchBuilder);
return app.Use(next => new MapUseMiddleware(next, branchBuilder, pathMatch).Invoke);
}
}
public class MapUseMiddleware
{
private readonly RequestDelegate _next;
private readonly PathString _pathMatch;
private readonly RequestDelegate _branch;
public MapUseMiddleware(RequestDelegate next, IApplicationBuilder branchBuilder, PathString pathMatch)
{
_next = next;
_pathMatch = pathMatch;
// this is registered at the end of the pipeline
branchBuilder.Use(subNext => { return ctx => next(ctx); });
_branch = branchBuilder.Build();
}
public async Task Invoke(HttpContext context)
{
PathString path = context.Request.Path;
PathString remainingPath;
if (path.StartsWithSegments(_pathMatch, out remainingPath))
{
// Update the path
PathString pathBase = context.Request.PathBase;
context.Request.PathBase = pathBase + _pathMatch;
context.Request.Path = remainingPath;
await _branch(context);
context.Request.PathBase = pathBase;
context.Request.Path = path;
}
else
{
await _next(context);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment