在ASP.NET Core

时间:2019-02-06 00:10:15

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

目标:在运行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. 似乎我只想在URL.net等“经典” .net中的global.asax中拥有内容。

我看到程序使用.UseStartup<Startup>();调用Startup.cs 是否有可能获得访问权限,以便能够终止GOAL以获取类似http://localhost:4444的URL

我想要的一切...

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

在类库/startup/program.cs中的.net核心时立即显示我的URL。cs将让我看到类似http://localhost:4444的URL

1 个答案:

答案 0 :(得分: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;