Reputation: 103
I would like to get the base Url of my .NET 6 Web Application server. The issue is that I want to get it in the Program.cs
file and not inside a Controller.
The reason for this is because Program.cs
is where i populate my database with objects and i would like to give these objects a string property that contains the current base Url of the website.
Is this possible?
Upvotes: 0
Views: 2729
Reputation: 3196
Since there is a lot going on during startup of the web application, you have not everything available at this time.
One thing you could do, is register a delegate when the ApplicationStarted
token has been canceled:
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Lifetime.ApplicationStarted.Register(() =>
{
ICollection<string> urls = app.Urls; // The list of URLs that the HTTP server is bound to
});
app.Run();
}
Upvotes: 1
Reputation: 2620
you can use this to get urls on which your application is listening but only after it is running.
You can try this. but I am not sure how it will fit into your solution.
await app.StartAsync();
Console.WriteLine($"Urls from Program.cs after app.StartAsync(): {string.Join(", ", app.Urls)}");
await app.WaitForShutdownAsync();
Upvotes: 0