Get original URL after rewriting in Kestrel

2019-07-29 23:22发布

问题:

Apache would choose a file to serve based on rewritten URL, but the original URL would be passed to the script.

Kestrel passes the rewritten URL down the pipeline (accessible via HttpContext.Request.Path).

Is it possible to access original URL from Middleware after it has been rewritten?

回答1:

Following the direction issued by @Tseng. My test wraps the RewriteMiddleware, but you may want a separate middleware.

public class P7RewriteMiddleware
{
    private RewriteMiddleware _originalRewriteMiddleware;

    public P7RewriteMiddleware(
        RequestDelegate next,
        IHostingEnvironment hostingEnvironment,
        ILoggerFactory loggerFactory,
        RewriteOptions options)
    {
        _originalRewriteMiddleware = new RewriteMiddleware(next, hostingEnvironment, loggerFactory, options);
    }

    /// <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 new Task Invoke(HttpContext context)
    {
        var currentUrl = context.Request.Path + context.Request.QueryString;
        context.Items.Add("original-path", currentUrl);
        return _originalRewriteMiddleware.Invoke(context);
    }
}

Later, my auth filter uses it.

if (spa.RequireAuth)
{
   context.Result = new RedirectToActionResult(Action, Controller,
         new { area = Area, returnUrl = context.HttpContext.Items["original-path"] });
}