Actually read AppSettings in ConfigureServices phase in ASP.NET Core

前端 未结 4 1295
刺人心
刺人心 2021-01-07 16:19

I need to setup a few dependencies (services) in the ConfigureServices method in an ASP.NET Core 1.0 web application.

The issue is that based on the new

4条回答
  •  無奈伤痛
    2021-01-07 17:06

    The appsettings.json file :

      "MyApp": {
        "Jwt": {
          "JwtSecretConfigKey": "jwtSecretConfigKey",
          "Issuer": "appIssuer",
          "Audience": "appAudience",
          "ExpireMinutes": 60
        }
      }
    

    add a class to bind Jwt section of "MyApp" ...

       public class JwtConfig
        {
            public string JwtSecretConfigKey { get; set; }
            public string Issuer { get; set; }
            public string Audience { get; set; }
            public int ExpireMinutes { get; set; }
        }
    

    In ConfigureServices method :

    //reading config from appsettings.json
    var jwtConfig = Configuration.GetSection("MyApp:Jwt").Get();
    
    //using config data ....
    services.AddJwt(new AddJwtOptions(jwtConfig.JwtSecretConfigKey, jwtConfig.Issuer, jwtConfig.Audience, jwtConfig.ExpireMinutes));
    

    The code below is the same as above. it works as well...

    var jwtConfig = Configuration.GetSection("MyApp").GetSection("Jwt").Get();
    

    Hope this helps..

提交回复
热议问题