gpt4 book ai didi

asp.net-core - 如何在Asp.Net Core中配置Startup类

转载 作者:行者123 更新时间:2023-12-02 04:06:23 25 4
gpt4 key购买 nike

我已阅读Working with multiple environments以及关于Startup类(class)。

When an ASP.NET Core application starts, the Startup class is used to bootstrap the application, load its configuration settings, etc. (learn more about ASP.NET startup). However, if a class exists named Startup{EnvironmentName} (for example StartupDevelopment), and the ASPNETCORE_ENVIRONMENT environment variable matches that name, then that Startup class is used instead. Thus, you could configure Startup for development, but have a separate StartupProduction that would be used when the app is run in production. Or vice versa.

所以我有3个启动类(class)StartupDevelopment , StartupStagingStartupProduction和我的Program.cs配置如下

public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<StartupDevelopment>()
.Build();

host.Run();
}
}

请注意.UseStartup<StartupDevelopment>()配置为StartupDevelopment

现在在StagingProduction我会设置ASPNETCORE_ENVIRONMENT因此 。然而Asp.Net core如何知道使用StartupStagingStartupProduction因为它被硬编码为 StartupDevelopment

最佳答案

an IWebHostBuilder.UseStartup(string assemblyName) extension method您可以使用它来加载正确的 Startup{ASPNETCORE_ENVIRONMENT} 类。定义后,here is the algorithm试图找到正确的类。

如果您不想对程序集名称进行硬编码,则可以像这样以编程方式获取它:

using System.Reflection; // Add this so you can use .GetTypeInfo()

public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup(typeof(StartupDevelopment).GetTypeInfo().Assembly.GetName().Name)
.Build();

host.Run();
}
}

为了使用此约定,所有 Startup* 类都需要位于同一个程序集中。

关于asp.net-core - 如何在Asp.Net Core中配置Startup类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39254937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com