How to get the Development/Staging/production Hosting Environment in ConfigureServices

前端 未结 12 1883
时光取名叫无心
时光取名叫无心 2020-12-04 15:51

How do I get the Development/Staging/production Hosting Environment in the ConfigureServices method in Startup?

public void ConfigureServices(IS         


        
12条回答
  •  遥遥无期
    2020-12-04 16:40

    In .NET Core 2.0 MVC app / Microsoft.AspNetCore.All v2.0.0, you can have environmental specific startup class as described by @vaindil but I don't like that approach.

    You can also inject IHostingEnvironment into StartUp constructor. You don't need to store the environment variable in Program class.

    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());
                }            
            });
    
            ......
        }
    }
    

提交回复
热议问题