Ik moet in de ConfigureServices
-methode controleren of de huidige naam van de hostingomgeving ‘Ontwikkeling’ is.
Dus het gebruik van de IHostingEnvironment.IsDevelopment()
-methode is misschien oké voor mij, maar in tegenstelling tot de Configure-methode heb ik geen IHostingEnvironment env
.
Antwoord 1, autoriteit 100%
maak gewoon een eigenschap in de klasse Startup om de IHostingEnvironment te behouden. Stel de eigenschap in de Startup-constructor in waar je al toegang toe hebt, dan heb je toegang tot de eigenschap vanuit ConfigureServices
Antwoord 2, autoriteit 26%
Hier gekopieerd van vraag gemarkeerd als duplicaat van deze en verwijderd. Met dank aan a-ctor.
Als u IHostingEnvironment
in ConfigureServices
wilt openen, moet u het via de constructor injecteren en opslaan voor latere toegang in ConfigureServices
:
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment environment)
{
Configuration = configuration;
Environment = environment;
}
public IConfiguration Configuration { get; }
public IHostingEnvironment Environment { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
System.Console.WriteLine($"app: {Environment.ApplicationName}");
}
// rest omitted
}
Antwoord 3, autoriteit 3%
IHostingEnvironment
is verouderd in Core 3.1
private readonly IWebHostEnvironment _env;
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
_env = env;
Configuration = configuration;
}
zou moeten lukken…
Refereer vervolgens overal met _env.IsDevelopment()
enz…
Antwoord 4
Als je geen Startup
-klasse gebruikt en .Configure()
rechtstreeks aanroept, heb je toegang tot de IHostingEnvironment
of IWebHostEnvironment
met behulp van GetService
:
ASP.NET Core 2.2:
.Configure(app => {
var hostingEnvironment = app.ApplicationServices.GetService<IHostingEnvironment>();
if (hostingEnvironment?.IsDevelopment() == true)
{
app.UseDeveloperExceptionPage();
}
// .. Other stuff
});
ASP.NET Core 3.x:
.Configure(app => {
var hostingEnvironment = app.ApplicationServices.GetService<IWebHostEnvironment>();
if (hostingEnvironment?.IsDevelopment() == true)
{
app.UseDeveloperExceptionPage();
}
// .. Other stuff
});
Antwoord 5
Als u geen Startup-klasse hebt (u maakt mogelijk een service), kunt u de omgeving als volgt ophalen van de hostContext in ConfigureServices:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
IConfiguration config = hostContext.Configuration;
Configuration = config;
var env = hostContext.HostingEnvironment;
EnvironmentName = env?.EnvironmentName;
...