简体   繁体   中英

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

Goal: To GET the URL in browser ASAP on running the ASP.NET Core 2.2 Web application.

What I tried was nearly every sort of hackery inside of Startup.cs , which sure you can use DI for registering the IHttpContextAccessor to get access to HttpContext

Some people will say to use

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

You can use this in a Controller, but if you go to definition you see that the HttpContext is coming from the ControllerBase of Mvc etc..

Seems to be several postings about this and no solutions.

  1. I am seeing to build middleware - great, but I don't know how to really do that
  2. I seen an article about middleware and call the Invoke Method, but How and Where etc..? Current URL in ASPCore Middleware?
  3. Seems like I just want what I had in global.asax in "classic" .net with the URL etc..

I see that Program calls Startup.cs with the .UseStartup<Startup>(); Is it possible to get access to be able to END GOAL to get the URL like http://localhost:4444

All I want ...

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

to show my URL as soon as .net core in a class library / startup / program.cs will let me see URL like http://localhost:4444

For handing request, you could try ASP.NET Core Middleware .

A simple middleware like below:

    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
        }
    }

For using GetDisplayUrl() , add

    using Microsoft.AspNetCore.Http.Extensions;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM