Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 952
Greedy Avatar asked Oct 10 '18 13:10

Greedy


People also ask

How do you host a startup in CS?

You cannot. Application startup happens only once, and long before any request has been received. In other words, there's no request to get information from. By “host” do you mean the domain name of the web service?

What ConfigureServices () method does in startup CS?

The startup class contains two methods: ConfigureServices(): Registers the services that your application will need. Configure(): Configures the middleware pipeline that controls how the application processes the HTTP requests and sends the response.

What does WebHost CreateDefaultBuilder () do?

CreateDefaultBuilder()Initializes a new instance of the WebHostBuilder class with pre-configured defaults.


1 Answers

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.
like image 54
Pavel Oganesyan Avatar answered Sep 22 '22 08:09

Pavel Oganesyan