正在 ASP.NET 核心网络应用中的 appsettings.json 加载 Hangfire 配置
Loading Hangfire configuration from appsettings.json in ASP.NET CORE web app
我正在尝试将 Hangfire 与 SQL 服务器一起使用,从 appsettings.json[=31= 读取连接字符串] 文件。它不起作用。只有当我向 UseSqlServerStorage 方法提供连接字符串时,它才有效。
这里是appsettings.json:
{
"ConnectionStrings": {
"HangfireDemo": "Data Source=VSQL64;Initial Catalog=HangfireDemo;Integrated Security=SSPI;"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
这里是 Startup.ConfigureServices 中配置 Hangfire 的行:
services.AddHangfire(configuration => configuration.UseSqlServerStorage("Data Source=VSQL64;Initial Catalog=HangfireDemo;Integrated Security=SSPI;"));
如果我在UseSqlServerStorage方法中写"HangfireDemo",是不行的。此方法中只有完整的连接字符串有效。
如何只提供连接字符串名称?
你应该可以这样做:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddHangfire(configuration =>
configuration.UseSqlServerStorage(Configuration.GetConnectionString("HangfireDemo"))
);
}
我正在尝试将 Hangfire 与 SQL 服务器一起使用,从 appsettings.json[=31= 读取连接字符串] 文件。它不起作用。只有当我向 UseSqlServerStorage 方法提供连接字符串时,它才有效。
这里是appsettings.json:
{
"ConnectionStrings": {
"HangfireDemo": "Data Source=VSQL64;Initial Catalog=HangfireDemo;Integrated Security=SSPI;"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
这里是 Startup.ConfigureServices 中配置 Hangfire 的行:
services.AddHangfire(configuration => configuration.UseSqlServerStorage("Data Source=VSQL64;Initial Catalog=HangfireDemo;Integrated Security=SSPI;"));
如果我在UseSqlServerStorage方法中写"HangfireDemo",是不行的。此方法中只有完整的连接字符串有效。
如何只提供连接字符串名称?
你应该可以这样做:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddHangfire(configuration =>
configuration.UseSqlServerStorage(Configuration.GetConnectionString("HangfireDemo"))
);
}