我需要在.NET核心(2.0)类库从appsettings.json文件中的值。有很多用于ASP.Net但对于.NET的核心解决方案。我appsettings.json像下面;
{
{
"serviceAccountEmail": "******@dotnet****.iam.gserviceaccount.com",
"Certificate": "*********.p12",
"secret": "*********",
"ImpersonatedUser": "*********@*********.com",
"GoogleApplicationName": "********"
}
}
你需要设置在你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安全设置
我定义的配置,被称为“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": {
...
},
...
}
配置类
然后,你需要定义配置类,这只是波苏斯,以表示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://stackoverflow.com/a/46940811/2343826