jsonsettings 中的 GetService 和 Configuration.GetSection 返回 null

迷惑者BB

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

在 startup.cs 文件中,我应该从 jsonsettings 文件中获取 Issuer、Key 和 Expiry Minutes,但无论我尝试做什么,GetService 或 Configutration.GetSection 每次都返回 null。而 ofc 这意味着 ValidIssuer 和 IssuerSigningKey 也是空的,这给了我错误“System.ArgumentNullException:字符串引用未设置为字符串的实例。” . 我会很感激一些建议:)

应用设置.json

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

启动.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;}
}
迷惑者BB

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

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

ActionFilterAttribute中的GetService返回null

Configuration.GetSection始终返回null

configuration.getValue或configuration.getsection始终返回null

单元测试中的HostBuilder:HostContext.Configuration.GetSection返回值null

Configuration.GetSection从appsetting.json获取值,但是Configuration.GetSection.Bind始终返回null

Package的GetService方法在vs2017扩展中返回null

Configuration.GetSection返回空值

IConfiguration.GetSection()作为属性返回null

Configuration.GetSection 返回文件中不存在的 ConfigurationSection

即使GetSection正在运行,ServiceCollection也会为IOptions返回null

PlatformUI.getWorkbench()。getService(IEventBroker.class)返回null

执行单元测试时,ConfigurationManager.GetSection(sectionName)返回null

CloudConfigurationManager.GetSetting()在Azure Configuration Manager 3.0中返回null

System.Configuration.ConnectionStringSettingsCollection.this [string] .get在类中返回null

找不到自定义BLE服务,mBluetoothGatt.getService(uuid)返回null

Asp.Net Core 2.0中的Configuration.GetSection获取所有设置

Nancy v2中的Nancy.Json.JsonSettings

ASP.Net-在选择中返回null和0

getAllCellInfo()和getAllCellInfo()在Android Oreo中返回null

TimePicker .getCurrentHour() 和 .getCurrentMinute() 在 api 19 中返回 null

配置GetSection返回对象部分的空值

context.RequestServices.GetService()解析为null

在HtmlAgilityPack中返回null

在输出中返回null

在方法中返回null

SpringBoot:Autowired在Configuration中有效,但在Controller中返回null

configuration.GetValue列表返回null

MyBatis 返回 emptyList() 和 null

使用手动添加到dotnet核心控制台应用程序的settings.json文件时,Configuration.GetSection(“ SectionName”)始终为null