ASP.NET Core 2.1 get current web hostname and port in Startup.cs

Greedy picture Greedy · Oct 10, 2018 · Viewed 8k times · Source

I want to register my WebAPI to Consul service discovery and for that I should provide URL of my WebAPI (for example: http://service1.com) and health check endpoint (http://service1.com/health/check). How can I get that URL?

I found this piece of code:

var features = app.Properties["server.Features"] as FeatureCollection;
var addresses = features.Get<IServerAddressesFeature>();
var address = addresses.Addresses.First();               
var uri = new Uri(address);

It returns 127.0.0.1:16478 instead of localhost:5600. I think first one used by dotnet.exe and second one is IIS which forwards 5600 to 16478. How can I get localhost:5600 in Startup.cs?

Answer

Pavel Oganesyan picture Pavel Oganesyan · Aug 1, 2019

I don't think it is possible since there is usually a reverse proxy in production that handles public address and the application itself should not be exposed to public and, therefore, be aware of public address. But there can be some workarounds:

  1. Place URL is some kind of config file that can be updated during deploy steps to have the correct URL.
  2. Application can get full URL of the request like this, so after first actual request to the application we can get hostname.