如何在启动中的ConfigureServices方法中获得开发/登台/生产托管环境?
public void ConfigureServices(IServiceCollection services)
{
// Which environment are we running under?
}
ConfigureServices方法只接受一个IServiceCollection参数。
如何在启动中的ConfigureServices方法中获得开发/登台/生产托管环境?
public void ConfigureServices(IServiceCollection services)
{
// Which environment are we running under?
}
ConfigureServices方法只接受一个IServiceCollection参数。
当前回答
由于还没有完整的复制和粘贴解决方案,基于Joe Audette的回答:
public IWebHostEnvironment Environment { get; }
public Startup(IWebHostEnvironment environment, IConfiguration configuration)
{
Environment = environment;
...
}
public void ConfigureServices(IServiceCollection services)
{
if (Environment.IsDevelopment())
{
// Do something
}else{
// Do something
}
...
}
其他回答
由于还没有完整的复制和粘贴解决方案,基于Joe Audette的回答:
public IWebHostEnvironment Environment { get; }
public Startup(IWebHostEnvironment environment, IConfiguration configuration)
{
Environment = environment;
...
}
public void ConfigureServices(IServiceCollection services)
{
if (Environment.IsDevelopment())
{
// Do something
}else{
// Do something
}
...
}
另一种方法是使用configuration ["ASPNETCORE_ENVIRONMENT"]直接从配置中读取环境名称。这适用于任何可以访问配置的地方。
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
Console.WriteLine(Configuration["ASPNETCORE_ENVIRONMENT"]);
}
前提条件是主机是用program .cs中的host . createdefaultbuilder()创建的,这是ASP. cs的默认值。NET Core 3.0(和5.0)web应用程序。如果使用其他构建器,则可以使用program .cs中的AddEnvironmentVariables()添加envars。
在. net Core 2.0 MVC app / Microsoft.AspNetCore.All v2.0.0中,你可以有@vaindil所描述的特定于环境的启动类,但我不喜欢这种方法。
你也可以在StartUp构造函数中注入IHostingEnvironment。不需要将环境变量存储在Program类中。
public class Startup
{
private readonly IHostingEnvironment _currentEnvironment;
public IConfiguration Configuration { get; private set; }
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
_currentEnvironment = env;
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
......
services.AddMvc(config =>
{
// Requiring authenticated users on the site globally
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
// Validate anti-forgery token globally
config.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
// If it's Production, enable HTTPS
if (_currentEnvironment.IsProduction()) // <------
{
config.Filters.Add(new RequireHttpsAttribute());
}
});
......
}
}
在NET6中,启动和程序合并为一个文件,启动中不再有ConfigureServices方法。现在你可以简单地使用
builder.Environment.IsProduction()
builder.Environment.IsStaging()
builder.Environment.IsDevelopment()
就在第一行之后
var builder = WebApplication.CreateBuilder(args);
如果你需要在你的代码库中某个不容易访问IHostingEnvironment的地方测试这个,另一个简单的方法是这样做的:
bool isDevelopment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development";