예제 #1
0
    /// <summary>
    /// Executes the middleware.
    /// </summary>
    /// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
    /// <returns>A task that represents the execution of this middleware.</returns>
    public Task Invoke(HttpContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        var rewriteContext = new RewriteContext
        {
            HttpContext        = context,
            StaticFileProvider = _fileProvider,
            Logger             = _logger,
            Result             = RuleResult.ContinueRules
        };

        var originalPath = context.Request.Path;

        RunRules(rewriteContext, _options, context, _logger);
        if (rewriteContext.Result == RuleResult.EndResponse)
        {
            return(Task.CompletedTask);
        }

        // If a rule changed the path we want routing to find a new endpoint
        if (originalPath != context.Request.Path)
        {
            if (_options.BranchedNext is not null)
            {
                // An endpoint may have already been set. Since we're going to re-invoke the middleware pipeline we need to reset
                // the endpoint and route values to ensure things are re-calculated.
                context.SetEndpoint(endpoint: null);
                var routeValuesFeature = context.Features.Get <IRouteValuesFeature>();
                if (routeValuesFeature is not null)
                {
                    routeValuesFeature.RouteValues = null !;
                }
                return(_options.BranchedNext(context));
            }
        }

        return(_next(context));
    }