ASPCore 中间件中的当前 URL?

Mic*_*ael 5 url-routing asp.net-mvc-routing asp.net-core-mvc asp.net-core

有没有办法可以在 ASPCore 2.0 中间件中访问当前请求的 URL?

有什么我可以注射的吗?

Shy*_*yju 9

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);
}
Run Code Online (Sandbox Code Playgroud)

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

using Microsoft.AspNetCore.Http.Extensions;
Run Code Online (Sandbox Code Playgroud)