AppSettings值始终为空净核心

时间:2018-10-18 18:29:42

标签: c# .net-core appsettings

尝试从json文件中获取值并将其使用IOptions <>类将其绑定到JwtSettings类时遇到问题,但是每次值均为null或0 启动类:

 public class Startup
{
    private readonly IOptions<JwtSettings> _settings;

    public Startup(IConfiguration configuration, IOptions<JwtSettings> settings)
    {
        Configuration = configuration;
        _settings = settings;
    }

    public IConfiguration Configuration { get; }

    public IContainer ApplicationContainer { get; private set; } 

    // This method gets called by the runtime. Use this method to add services to the container.
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.AddOptions();
        services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
        services.AddJwt(_settings);
        var builder = new ContainerBuilder();
        //register commandModules 
        builder.Populate(services);
        builder.RegisterModule(new ContainerModules(Configuration));
        ApplicationContainer = builder.Build();

        return new AutofacServiceProvider(ApplicationContainer);
    }

使用“选项”时的扩展方法:

        public static void AddJwt(this IServiceCollection services, IOptions<JwtSettings> setting)
    {
        IConfiguration configuration;
        using (var serviceProvider = services.BuildServiceProvider())
        {
            configuration = serviceProvider.GetService<IConfiguration>();
        }
        services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(cfg =>
            {
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(setting.Value.Key)),
                    ValidIssuer = setting.Value.Issuer,
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime = true
                };
            });
    }

在程序类上,我在构建Web主机以指定应用程序的配置时添加调用ConfigureAppConfiguration

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.SetBasePath(Directory.GetCurrentDirectory());
                config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false);
                config.AddCommandLine(args);
            })
            .UseStartup<Startup>();

json appsettings看起来是: enter image description here

2 个答案:

答案 0 :(得分:0)

我没有看到您是否正在从appsettings.json中读取配置。您在哪里指定的?像这样:

var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();

 Configuration = builder.Build();

如果您有多个设置。像(appsettings.Development.json),产品等。

  var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

您需要检查应用程序的环境变量。您的IConfiguration应该从那里获取各个部分

enter image description here

例如,如果您已将其部署在IIS上,请在此处检查:

enter image description here

enter image description here

答案 1 :(得分:0)

您认为当时没有填充构造函数参数ConfigureServices。当调用构造函数JwtSettings时,该方法尚未执行,因此该框架除了默认值services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));之外,没有其他东西可以注入到构造函数中。

即使您调用IOptions<JwtSettings>也不会填充ConfigureServices,因为它已经被注入到构造函数中了-框架不会更新或重新注入该值。这意味着您必须自己在public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings")); services.AddJwt(Configuration); services .AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } public static void AddJwt(this IServiceCollection services, IConfiguration configuration) { var settings = configuration.GetSection("JwtSettings").Get<JwtSettings>(); .... } (或扩展方法)中阅读设置,然后才能使用这些值。例如

ConfigureServices

完成IOptions<JwtSettings>方法后,您可以将IOptions<JwtSettings>注入控制器/服务中,并将被填充。

我知道这不像使用wget参数那样干净,但是您正在尝试在DI系统初始化之前使用它,因此此时您需要手动阅读设置。