在 .Net Core 类库中从 appsettings.json 读取常量

3

我需要从appsettings.json文件中获取值,该文件在.Net Core(2.0)类库中。有许多解决方案适用于ASP.Net,但并不适用于.Net Core。我的appsettings.json如下所示;

{
   {

    "serviceAccountEmail": "******@dotnet****.iam.gserviceaccount.com",
    "Certificate": "*********.p12",
    "secret": "*********",
    "ImpersonatedUser": "*********@*********.com",
    "GoogleApplicationName": "********"
    }
}
1个回答

3

您需要在Startup配置中设置此项。

public class Startup
{
    private readonly IConfiguration _config;

    public Startup(IConfiguration config)
    {
        _config = config;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        var value = _config["key"];
    }

    public void Configure(IApplicationBuilder app, IConfiguration config)
    {
        var value = config["key"];
    }
}

MS文档:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2#access-configuration-during-startup

关注点分离

如果你将解决方案分成多个项目并使用类库,Microsoft.Extensions.Options.ConfigurationExtensions包可以轻松读取appsettings文件中的值,并将其注入到项目中的配置类中。

该包有两个扩展可供使用:

public static T Get<T>(this IConfiguration configuration);
public static IServiceCollection Configure<TOptions>(this IServiceCollection services, 
    IConfiguration config) where TOptions : class;

示例:

我将所有与安全相关的服务使用 Microsoft.AspNetCore.Identity 放入名为 DL.SO.Services.Security 的项目中。

appsettings.json 中的安全设置

我在我的 web/start-up 项目中定义了一个名为 "AppIdentitySettings" 的配置,用于设置我想要在 ASP.NET Core Identity 框架中设置的身份验证选项。

{
    "ConnectionStrings": {
        ...
    },
    "AppIdentitySettings": {
        "User": {
            "RequireUniqueEmail": true
        },
        "Password": {
            "RequiredLength": 6,
            "RequireLowercase": true,
            "RequireUppercase": true,
            "RequireDigit": true,
            "RequireNonAlphanumeric": true
        },
        "Lockout": {
            "AllowedForNewUsers": true,
            "DefaultLockoutTimeSpanInMins": 30,
            "MaxFailedAccessAttempts": 5
        }
    },
    "Recaptcha": {
        ...
    },
    ...
}

配置类

然后您需要定义配置类,它们只是 POCOs(Plain Old CLR Object),用于表示 appsettings.json 中的配置结构。配置类的名称不必与您在 appsettings.json 中定义的部分名称匹配,而是属性的名称需要匹配。

namespace DL.SO.Services.Security
{
    public class AppIdentitySettings
    {
        public UserSettings User { get; set; }
        public PasswordSettings Password { get; set; }
        public LockoutSettings Lockout { get; set; }
    }

    public class UserSettings
    {
        public bool RequireUniqueEmail { get; set; }
    }

    public class PasswordSettings
    {
        public int RequiredLength { get; set; }
        public bool RequireLowercase { get; set; }
        public bool RequireUppercase { get; set; }
        public bool RequireDigit { get; set; }
        public bool RequireNonAlphanumeric { get; set; }
    }

    public class LockoutSettings
    {
        public bool AllowedForNewUsers { get; set; }
        public int DefaultLockoutTimeSpanInMins { get; set; }
        public int MaxFailedAccessAttempts { get; set; }
    }
}

以下是来自于并更加详细的内容:https://dev59.com/QFYN5IYBdhLWcg3wxqhu#46940811

1
在这个解决方案中,值是从一个主方法调用的,在我的情况下,这些值应该从一个类库中读取 - 这意味着没有主方法。 - AshleyCam
@AshleyCam在答案中进行了修订。 - Fraze
嗨,在我的场景中,我有一个解决方案中的不同项目,我的appsetting.json在解决方案的MVC项目中,其余在类库项目中。在这种情况下,如何使用DI访问配置设置以在整个项目中使用相同的appsetting.json。MVC代码通过创建对象ClassName obj = new ClassName()来访问我的类库。由于我为类定义了带参数的构造函数以访问配置设置,因此我会得到所有明显原因的编译时错误。是否有任何方法可以实现这一点,因为我已经尝试了很多解决方案。 - Aditya Pewekar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接