ASP 核心中间件中的当前 URL?

Current URL in ASPCore Middleware?

有什么方法可以在 ASP Core 2.0 中间件中访问当前请求的URL?

有什么可以注射的吗?

你的中间件得到 HttpContext context 其中有

//
// Summary:
//     /// Gets the Microsoft.AspNetCore.Http.HttpRequest object for this request. ///
public abstract HttpRequest Request { get; }

因此您可以通过以下方式获得所有需要的信息:

app.Use(async (context, next) =>
{
    //context.Request.Path
    //context.Request.QueryString
    ...

    await next.Invoke();

});

HttpContext 对象将传递给中间件的 Invoke 方法。您可以访问 Request 属性。

您可以使用 GetDisplayUrl 扩展方法或 GetEncodedUrl 扩展方法。

public Task Invoke(HttpContext context)
{
    var url1 =context.Request.GetDisplayUrl();
    var url2  = context.Request.GetEncodedUrl();       


    // Call the next delegate/middleware in the pipeline
    return this._next(context);
}

这 2 个扩展方法在 Microsoft.AspNetCore.Http.Extensions 命名空间中定义。所以确保你有一个 using 语句来包含命名空间

using Microsoft.AspNetCore.Http.Extensions;