如何将 appsetting.json 配置文件中的 IConfiguration 注入到他的代码中



在这里阅读官方文档后,我仍然不明白如何加载和使用这些appsetting.json配置文件。从理论上讲,一切似乎都是合乎逻辑的,但是当我尝试在我的课堂上设置它时,我遇到了问题。

让我先给你一部分代码。对于那些我知道我在 IndentityServer4 实现中执行此操作的人,但我需要在 API 和客户端中执行相同的操作。

我修改了 Program.cs 文件以包含这种加载配置文件的新方法,如文档中所述:

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    config.SetBasePath(Directory.GetCurrentDirectory());
                    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false);
                })
                .UseStartup<Startup>();
    }

我在我的 Statup 中没有做任何与配置相关的操作.cs

    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddIdentityServer()
                .AddDeveloperSigningCredential(persistKey: false)
                .AddTestUsers(Config.GetUsers())
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryClients(Config.GetClients());
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseIdentityServer();
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }
    }

最后是我的 Config.cs,或者我的配置文件的一部分。这是我想使用我的配置的这个。比方说,为了简单起见,我想从我的配置文件加载我所有的字符串。

    public static class Config
    {
        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>()
            {
                new Client
                {
                    ClientName = "xxxxxxxx",
                    ClientId = "f26ee5d6-xxxx-xxxx-xxxx-xxxx0efa43d9.local.app",
                    AllowedGrantTypes = GrantTypes.Code,
                    AllowOfflineAccess = true,
                    IdentityTokenLifetime = 60 * 60 * 24,
                    AccessTokenLifetime = 60 * 60 * 24,
                    RedirectUris = new List<string>()
                    {
                        "https://www.getpostman.com/oauth2/callback"
                    },
                    PostLogoutRedirectUris = new List<string>()
                    {
                        "https://www.getpostman.com"
                    },
                    AllowedCorsOrigins = new List<string>()
                    {
                        "https://www.getpostman.com"
                    },
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "xxxxxx",
                    },
                    ClientSecrets = new List<Secret>
                    {
                        new Secret("XXXXXXXX".Sha256())
                    },
                    AllowAccessTokensViaBrowser = true,
                    RequireConsent = false,
                    EnableLocalLogin = true,
                    Enabled = true
                }
             };
        }
    }

您可能注意到我的配置.cs是静态的,并且可能由我无法处理的代码加载。所以我不知道如何在这里"注入"这个配置。

创建映射到设置的强类型对象模型

public class MySettings {
    //Properties here
}

IConfiguration注入Startup

private IConfiguration configuration;
public Startup(IConfiguration configuration) {
    this.configuration = configuration;
}

使用配置绑定到对象模型并将其显式注入到依赖方法

public void ConfigureServices(IServiceCollection services) {
    MySettings settings = configuration.GetSection("Section_Name_Here").Get<MySettings>();
    services.AddMvc();
    services.AddIdentityServer()
        .AddDeveloperSigningCredential(persistKey: false)
        .AddTestUsers(Config.GetUsers())
        .AddInMemoryIdentityResources(Config.GetIdentityResources())
        .AddInMemoryApiResources(Config.GetApiResources())
        .AddInMemoryClients(Config.GetClients(settings)); //<--
}

依赖方法将相应地重构

public static IEnumerable<Client> GetClients(MySettings settings) {
    return new List<Client>() {
        new Client {
            ClientName = settings.ClientName,
            //...omitted for brevity

相关内容

  • 没有找到相关文章

最新更新