【问题标题】:How to pull configuration options out of method body and use configuration class in Dot Net Core 3.1如何从方法主体中提取配置选项并在 Dot Net Core 3.1 中使用配置类
【发布时间】:2020-08-07 13:12:08
【问题描述】:

这里是菜鸟。我遵循了 IdentityServer 4 的快速入门。我正在清理代码。我正在使用网络核心 3.1。我的 Startup.ConfigureServices 变得拥挤,我想清理它并将配置选项、值放入一个类中——就像 IdentityServer 4 为 IdentityResources、ApiScopes、ApiResources 和客户端配置选项使用一个类一样。

我阅读了许多博客文章,并从https://andrewlock.net/avoiding-startup-service-injection-in-asp-net-core-3/ 中看到了如何为自定义服务添加配置到 IoC 容器,但我还没有找到一种方法来提取框架服务的选项/值,例如 Identity核心,或 services.AddAuthentication().AddOpenIdConnect() 例如。


    services.AddAuthentication(options =>
    {
      options.DefaultScheme = "Cookies";
      options.DefaultChallengeScheme = "oidc";
    })
    .AddCookie("Cookies", options =>
    {
      options.AccessDeniedPath = "/account/denied";
    })
    .AddOpenIdConnect("oidc", options =>
    {
        /***  HOW DO I PUT THE BELOW KEY/VALUES INTO A CONFIG CLASS  ***/

        options.Authority = "https://demo.identityserver.io";
        options.ClientId = "server.hybrid";
        options.ClientSecret = "secret";
        options.ResponseType = "code id_token";
 
        options.SaveTokens = true;
                    
        options.Scope.Clear();
        options.Scope.Add("openid");
                    
        options.TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name", 
            RoleClaimType = "role"
        };
    });

然后像这样使用那个配置类


var builder = services.AddIdentityServer()
    .AddInMemoryIdentityResources(Config.IdentityResources) <-- From the Config class
    .AddInMemoryApiScopes(Config.ApiScopes) <-- From the Config class
    .AddInMemoryClients(Config.Clients); <-- From the Config class

所以如果我的问题不清楚,我该如何创建一个 Config 类并将该类传递给 .AddOpenIdConnect(MyConfigClass) 以清理 ConfigureServices 方法(IoC 容器?)

上面的代码是在 IoC 容器中配置服务的最佳/最干净的方式吗?是我在 Andrew Lock 的博客文章中寻找的答案,我只是不明白吗?我假设我可以像使用 IS4 .AddInMemoryIdentityResources 一样将一个类传递给 .AddOpenIdConnect 扩展方法

感谢您的帮助。

【问题讨论】:

    标签: c# configuration .net-core-3.1


    【解决方案1】:

    所有 Microsoft 服务都遵循相同的 Options pattern。首先,您可以将这些 lambda 方法移动到静态方法,可能在不同的类上。这似乎是您的Config 示例所做的。您只需要确保您的静态方法具有相同的函数签名。

    例如,.AddAuthenticationAction&lt;AuthenticationOptions&gt; 委托作为参数。所以任何static void foo(AuthenticationOptions o) 方法都可以被传入。

    或者您可以编写实现IConfigureOptions&lt;T&gt; 的服务并注册它们。如果您需要访问其他服务(例如数据库)以配置这些选项类型,这将特别有用。

    【讨论】:

    • 谢谢老兄。事实证明,尽管我需要使用参数类型的 OpenIdConnectOptions 而不是 AuthenticationOptions (对于 .AddOpenIdConnect 扩展方法),但我还是选择了 Jeremy 的回答。对于 .AddAuthentication 扩展方法,Jeremy 的回答很到位。
    猜你喜欢
    • 1970-01-01
    • 2020-08-22
    • 2020-08-20
    • 2018-12-21
    • 2020-07-30
    • 2020-06-15
    • 1970-01-01
    • 2020-06-28
    • 2020-11-24
    相关资源
    最近更新 更多