如何在应用程序启动时获取请求URL [英] How to get the request URL on application startup

查看:231
本文介绍了如何在应用程序启动时获取请求URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在应用程序启动时在我的Startup.cs文件中查找请求URL(特别是域).

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 = "";
}

我需要在Startup.cs文件中使用它,因为它将确定稍后在启动类的ConfigureServices方法中添加了哪些临时服务.

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?

推荐答案

不幸的是,您无法检索应用程序的托管URL,因为该位由IIS/WebListener等控制,并且不会直接传递到应用程序

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.

现在,一个不错的选择是为每个服务器提供一个ASPNET_ENV环境变量,然后分隔您的逻辑.以下是一些有关如何使用它的示例:

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
    }
}


这是当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.
    }
}

希望这会有所帮助.

这篇关于如何在应用程序启动时获取请求URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆