Почему AppSettingsSection .Get <T>имеет значение null? - PullRequest
0 голосов
/ 15 апреля 2020

Я пытаюсь реализовать аутентификацию на основе jwt для моего веб-API в ASP. net, и я довольно новичок в этом.

У меня проблема с получением конфигурации .GetSection.Get (где он становится нулевым) Код ниже показывает фрагмент моего Starup.cs.

Пожалуйста, посмотрите код ниже для лучшего понимания.

namespace DBService
{
    public class Startup
    {
        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
        private readonly ILogger<Startup> _logger;

        public Startup(ILogger<Startup> logger, IConfiguration configuration)
        {
            _logger = logger;
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                builder =>
                {
                    builder.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                    //builder.WithOrigins("*");
                });
            });

            var appSettingsSection = Configuration.GetSection("AppSettings");
            services.Configure<AppSettings>(appSettingsSection);

            // configure jwt authentication
            var appSettings = appSettingsSection.Get<AppSettings>();
            var key = Encoding.ASCII.GetBytes(appSettings.Secret);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

            services.AddScoped<AccountService>();
            //other addscoped here
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddMvc().AddControllersAsServices();

            var filePath = Path.Combine(System.AppContext.BaseDirectory, "DBService.xml");
            //var filePath = "./DBService.xml";
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "C# Backend Microservice", Version = "v1" });

                c.IncludeXmlComments(filePath);
                c.OperationFilter<FileUploadOperation>();
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseSwagger();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "C# Backend Microservice");
            });
            app.UseCors(MyAllowSpecificOrigins);
            app.UseHttpsRedirection();

            app.UseAuthentication();
            app.UseMvc();

            /*app.MapWhen(x => (!x.Request.Path.Value.StartsWith("/api") && !x.Request.Path.Value.StartsWith("/swagger")), builder =>
            {
                app.UseSpa(spa =>
                {
                    spa.Options.SourcePath = "redux-stylemanager";

                    //spa.UseReactDevelopmentServer(npmScript: "build");
                    spa.UseReactDevelopmentServer(npmScript: "start");
                });
            });*/
        }
    }
}

Пока это мои текущие настройки приложений . json

{
  "ConnectionStrings": {
    "EmailDb": "mongodb://localhost:27017"
  },
  "AppSettings": {
    "Secret":  "TEST SECRET"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Наконец, мой класс AppSettings определен следующим образом:

namespace MOHK_DBService.Utilities
{
    public class AppSettings
    {
        public string Secret { get; set; }
    }
}
...