using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Owin; using Microsoft.Owin.Mapping; namespace Custom.Owin.Authentication.Infrastructure { internal class MapMiddlewareEx { private readonly Func, Task> _next; private readonly MapOptions _options; public MapMiddlewareEx(Func, Task> next, MapOptions options) { if (next == null) { throw new ArgumentNullException(nameof(next)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } _ = options.PathMatch; _next = next; _options = options; } public Task Invoke(IDictionary environment) { OwinContext context = new OwinContext(environment); PathString path = context.Request.Path; if (path.StartsWithSegments(_options.PathMatch, out var remaining)) { return InvokeCore(environment, context, remaining, path); } return _next(environment); } private async Task InvokeCore(IDictionary environment, OwinContext context, PathString remaining, PathString path) { PathString pathBase = context.Request.PathBase; context.Request.PathBase = pathBase + _options.PathMatch; context.Request.Path = remaining; await _options.Branch(environment); context.Request.PathBase = pathBase; context.Request.Path = path; } } }