GetService 和 Configuration.GetSection 来自 jsonsettings returns null

GetService and Configuration.GetSection from jsonsettings returns null

我一直在关注一些关于 .net 等编程的教程,它有点过时了,还有关于 JWT 的部分,我被卡住了,因为我相信教程展示了它的完成方式在 .net 2.0 等之前(在 Configure 方法中,而不是在 app.UseJwtBearerAuthentication 的 ConfigureServices 中)。

在 startup.cs 文件中,我应该从 jsonsettings 文件中获取 Issuer、Key 和 Expiry Minutes,但无论我尝试做什么,每次 GetService 或 Configutration.GetSection returns null .而且这意味着 ValidIssuer 和 IssuerSigningKey 也为 null,这给了我错误 "System.ArgumentNullException: String reference not set to an instance of a String."。如果能提供一些建议,我将不胜感激:)

Appsettings.json

{
  "Logging": {
    "Console":{
      "LogLevel": {
        "Default": "Warning"
    },
    "IncludeScopes": false
  },
  "general": {
    "name": "Passenger"
  },
  "Jwt": {
    "Key": "key",
    "Issuer": "http://localhost:5000",
    "expiryMinutes": 5
  } 
}}

Startup.cs

...    
public class Startup
        {
   
    public IContainer ApplicationContainer {get; private set;}
    public Startup(IWebHostEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

     public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddOptions();
        //services.AddRazorPages();

        //var config = Configuration;
        //var settings = Configuration.GetSection("JwtSettings").Get<JwtSettings>();
        

        var sp = services.BuildServiceProvider();
        var jwtSettings = sp.GetService<JwtSettings>();

        // var appSettingsSection = Configuration.GetSection("JwtSettings");
        

        // services.Configure<JwtSettings>(appSettingsSection); //get key from appSettings 
        // var appSettings = appSettingsSection.Get<JwtSettings>(); 
        // var key = Encoding.UTF8.GetBytes(appSettings.Key); 

        services.AddAuthorization(options =>
        {
            options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
                .RequireAuthenticatedUser()
                .Build();
        }
        );

        services.AddAuthentication(option =>
       {
           option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
           option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

       })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {

                    ValidateIssuer = true,
                    ValidateLifetime = false,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = jwtSettings.Issuer,
                    ValidateAudience = false,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Key))
                };
            });

        var builder = new ContainerBuilder();
        builder.Populate(services);
        builder.RegisterModule(new ContainerModule(Configuration));
        builder.RegisterModule(new SettingsModule(Configuration));
        ApplicationContainer = builder.Build();

        return new AutofacServiceProvider(ApplicationContainer);

    }
...

JwtSettings.cs

public class JwtSettings
{
    public string Key {get; set;}
    public string Issuer {get; set;}
    public int ExpiryMinutes {get; set;}
}

实际上我都归结为 appsettings.json 文件格式错误。 我少了一个“}”,它无法正确读取它。我也用过

var signingKey = Configuration.GetSection("JwtSettings:Key").Value;

 var issuer = Configuration.GetSection("JwtSettings:Issuer").Value;

为了获得所需的值并且有效,我不再收到错误 500,而是收到错误 401,这是预期的。