Get original URL after rewriting in Kestrel

2019-07-29 23:55发布

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条回答
\"骚年 ilove
2楼-- · 2019-07-30 00:25

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"] });
}
查看更多
登录 后发表回答