简体   繁体   中英

GetService and Configuration.GetSection from jsonsettings returns null

I've been following some tutorial about programming in .net etc., and it is a little bit outdated, and there's a part about JWT, where I got stuck, because tutorial shows the way it was done I believe before .net 2.0 etc. (in the Configure method, not in ConfigureServices with app.UseJwtBearerAuthentication).

In the startup.cs file, I am suppossed to get Issuer, Key and Expiry Minutes from jsonsettings file, but whatever I try to do, GetService or Configutration.GetSection returns null everytime. And ofc that means that ValidIssuer and IssuerSigningKey are also null, which gives me error "System.ArgumentNullException: String reference not set to an instance of a String." . I would be grateful for some kind of advice:)

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;}
}

I all came down to wrong formatting of the appsettings.json file actually. I was missing one "}", and it couldn't read it properly. I also used

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

and

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

to get needed values and that worked, I don't get ERROR 500 anymore, but ERROR 401, which was expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM