在 ASP.NET 核心中尽快获取当前 URL program.cs / startup.cs

Get Current URL as soon as available program.cs / startup.cs in ASP.NET Core

目标:尽快在 运行 ASP.NET Core 2.2 Web 应用程序的浏览器中获取 URL。

我尝试了 Startup.cs 中几乎所有类型的 hackery,确保您可以使用 DI 注册 IHttpContextAccessor 以访问 HttpContext

有人会说用

var url = HttpContext?.Request?.GetDisplayUrl();

您可以在 Controller 中使用它,但是如果您查看定义,您会看到 HttpContext 来自 Mvc 等的 ControllerBase。

好像有好几篇关于这个的帖子,都没有解决办法。

  1. 我正在构建中间件 - 很好,但我不知道如何真正做到这一点
  2. 我看到一篇关于中间件的文章并调用了 Invoke 方法,但是如何以及在哪里等..?
  3. 似乎我只想要 "classic" .net 中 global.asax 中的内容以及 URL 等。

我看到程序用 .UseStartup<Startup>(); 调用 Startup.cs 是否有可能获得访问权限以结束目标以获得 URL 之类的 http://localhost:4444

我想要的...

var url = HttpContext?.Request?.GetDisplayUrl(); 

一旦 .net 核心在 class 库/启动/program.cs 中显示我的 URL 就会让我看到 URL 就像 http://localhost:4444

对于处理请求,您可以尝试ASP.NET Core Middleware

一个像下面这样的简单中间件:

    public class Startup
    {
        //rest code

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.Use((context,next) =>
            {
                var url = context.Request.GetDisplayUrl();
                return next.Invoke();
            });

            //rest code
        }
    }

要使用 GetDisplayUrl(),请添加

    using Microsoft.AspNetCore.Http.Extensions;