Search code examples
c#asp.net-coreasp.net-core-mvcurl-routingasp.net-mvc-routing

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


Solution

  • 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;