How to get the request URL on application startup

与世无争的帅哥 提交于 2019-12-10 03:00:58

问题


I'm trying to find the request URL (the domain specifically) when the application starts, in my Startup.cs file..

public Startup(IHostingEnvironment env)
{
   Configuration = new Configuration().AddEnvironmentVariables();
   string url = "";
}

I need it in the Startup.cs file because it will determine what transient services are added later in the startup class, in the ConfigureServices method.

What is the correct way of getting this information?


回答1:


Sadly you are unable to retrieve the hosting URL of your application since that bit is controlled by IIS/WebListener etc. and doesn't flow through to the application directly.

Now a nice alternative is to provide each of your servers with an ASPNET_ENV environment variable to then separate your logic. Here's some examples on how to use it:

Startup.cs:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        // Will only get called if there's no method that is named Configure{ASPNET_ENV}.
    }

    public void ConfigureDev(IApplicationBuilder app)
    {
        // Will get called when ASPNET_ENV=Dev
    }
}

Here's another example when ASPNET_ENV=Dev and we want to do class separation instead of method separation:

Startup.cs:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        // Wont get called.
    }

    public void ConfigureDev(IApplicationBuilder app)
    {
        // Wont get called
    }
}

StartupDev.cs

public class StartupDev // Note the "Dev" suffix
{
    public void Configure(IApplicationBuilder app)
    {
        // Would only get called if ConfigureDev didn't exist.
    }

    public void ConfigureDev(IApplicationBuilder app)
    {
        // Will get called.
    }
}

Hope this helps.




回答2:


This won't give you the domain but may help if you're just running on a port and need access to that:

        var url = app.ServerFeatures.Get<Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature>().Addresses.Single();

Not sure what happens if you have multiple addresses bound.



来源:https://stackoverflow.com/questions/28223565/how-to-get-the-request-url-on-application-startup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!