【问题标题】:Get Current URL as soon as available program.cs / startup.cs in ASP.NET CoreASP.NET Core 中的 program.cs / startup.cs 可用时立即获取当前 URL
【发布时间】:2019-02-06 00:10:15
【问题描述】:

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

我尝试的是 Startup.cs 内部的几乎所有类型的黑客,确保您可以使用 DI 注册 IHttpContextAccessor 以访问 HttpContext

有人会说要用

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

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

似乎有几个关于这个的帖子,没有解决方案。

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

我看到程序使用 .UseStartup<Startup>(); 调用 Startup.cs 是否可以访问 END GOAL 以获取像 http://localhost:4444 这样的 URL

我想要的一切......

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

在类库/startup/program.cs 中的 .net 核心让我看到像 http://localhost:4444 这样的 URL

【问题讨论】:

  • 你所要求的基本上没有任何意义。 WebHost 只是简单地回复请求。它可以向任何域 回复相同的值,除非您在代码中特别指定。这就像问汽车销售人员他们接下来要卖什么车......在有人问他们特定汽车之前,他们怎么知道?

标签: c# asp.net-core asp.net-core-mvc url-routing asp.net-mvc-routing


【解决方案1】:

对于处理请求,您可以尝试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;

【讨论】:

  • 实际上,如果我使用上面的代码并在 app.Use 和 F11 上设置断点,它永远不会进入内部,我想我需要编写一个带有调用方法的类?
猜你喜欢
  • 1970-01-01
  • 2020-05-25
  • 2019-03-15
  • 2016-12-09
  • 1970-01-01
  • 2018-10-03
  • 2017-02-22
  • 2020-07-11
  • 2016-08-07
相关资源
最近更新 更多