95

使用 ASP.NET Mvc Core 我需要将我的开发环境设置为使用 https,所以我Main在 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();

如何访问此处的托管环境,以便有条件地设置协议/端口号/证书?

理想情况下,我会使用 CLI 来操作我的托管环境,如下所示:

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

但似乎没有办法从命令行使用证书。

4

3 回答 3

185

我认为最简单的解决方案是从ASPNETCORE_ENVIRONMENT环境变量中读取值并将其与Environments.Development

var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var isDevelopment = environment == Environments.Development;
于 2017-06-08T13:58:36.760 回答
28

这是我的解决方案(为 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();
}
于 2018-07-05T16:01:24.897 回答
7

在 .NET 核心 3.0 中

using System;
using Microsoft.Extensions.Hosting;

然后

var isDevelopment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == Environments.Development;
于 2020-07-08T04:05:04.137 回答