fatih
fatih

Reputation: 229

How to get host name in startup file

My API is running on IIS with "www.api-example.com". How can I get "api-example" in startup file ConfigureServices method?

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        //string hostName = ...

        //*** App Settings Services
        services.AddAppServices(Configuration);

        //*** Business Services
        services.AddBusinessServicesCollection();
         
    }
}

Upvotes: 0

Views: 625

Answers (2)

Md Farid Uddin Kiron
Md Farid Uddin Kiron

Reputation: 22539

My API is running on IIS with "www.api-example.com". How can I get "api-example" in startup file ConfigureServices method?

No we cannot, because ConfigureServices invocked before constructing Startup so if we try to inject, it will through exception, even if we declare at global variable in that scenario it will always be null. Application startup happens only once, and long before any request has been received.

Proper Way to Get Main Host/Domain Name:

          app.Use((context, next) =>
            {
               var hostUrl = context.Request.Host.Host;
                Console.WriteLine(hostUrl);
                return next.Invoke();
            });

Output:

enter image description here

Upvotes: 2

Albin C S
Albin C S

Reputation: 348

app.Use((context,next) =>
 {
    var url = context.Request.GetDisplayUrl();
    return next.Invoke();
 });

host name link

Upvotes: 0

Related Questions