Access environment name in Program.Main in ASP.NET Core

。_饼干妹妹 提交于 2019-12-09 14:00:11

问题


Using ASP.NET Mvc Core I needed to set my development environment to use https, so I added the below to the Main method in Program.cs:

var host = new WebHostBuilder()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .UseKestrel(cfg => cfg.UseHttps("ssl-dev.pfx", "Password"))
                .UseUrls("https://localhost:5000")
                .UseApplicationInsights()
                .Build();
                host.Run();

How can I access the hosting environment here so that I can conditionally set the protocol/port number/certificate?

Ideally, I would just use the CLI to manipulate my hosting environment like so:

dotnet run --server.urls https://localhost:5000 --cert ssl-dev.pfx password

but there doesn't seem to be way to use a certificate from the command line.


回答1:


I think the easiest solution is to read the value from the ASPNETCORE_ENVIRONMENT environment variable and compare it with EnvironmentName.Development:

var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var isDevelopment = environment == EnvironmentName.Development;



回答2:


This is my solution (written for ASP.NET Core 2.1):

public static void Main(string[] args)
{
    var host = CreateWebHostBuilder(args).Build();

    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        var hostingEnvironment = services.GetService<IHostingEnvironment>();

        if (!hostingEnvironment.IsProduction())
           SeedData.Initialize();
    }

    host.Run();
}


来源:https://stackoverflow.com/questions/44437325/access-environment-name-in-program-main-in-asp-net-core

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