我需要从.Net Core(2.0)类库中的appsettings.json文件中获取值。有很多针对ASP.Net的解决方案,但没有针对.Net Core的解决方案。我的appsettings.json如下;
{
{
"serviceAccountEmail": "******@dotnet****.iam.gserviceaccount.com",
"Certificate": "*********.p12",
"secret": "*********",
"ImpersonatedUser": "*********@*********.com",
"GoogleApplicationName": "********"
}
}
答案 0 :(得分:0)
您需要在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"];
}
}
关注点分离
如果使用类库将解决方案分为多个项目,则 Microsoft.Extensions.Options.ConfigurationExtensions 包将很方便地从appsettings
文件中读取值并将其注入项目中的配置类。
它有2个可以使用的扩展名:
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 /启动项目的ASP.NET Core Identity
框架中设置的身份选项定义称为“ AppIdentitySettings”的配置。
{
"ConnectionStrings": {
...
},
"AppIdentitySettings": {
"User": {
"RequireUniqueEmail": true
},
"Password": {
"RequiredLength": 6,
"RequireLowercase": true,
"RequireUppercase": true,
"RequireDigit": true,
"RequireNonAlphanumeric": true
},
"Lockout": {
"AllowedForNewUsers": true,
"DefaultLockoutTimeSpanInMins": 30,
"MaxFailedAccessAttempts": 5
}
},
"Recaptcha": {
...
},
...
}
配置类
然后,您需要定义配置类(仅是POCO),以在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; }
}
}