在我的.net core mvc(2.2)应用程序中,我有一个配置,是从数据库配置的。例如,在更改数据库中的某些值之后,如何从控制器重新加载配置?我已经尝试过类似的方法,但是它不起作用:
MyConfiguration.cs:
public class MyConfiguration
{
public string SmtpServer {get;set;}
}
Startup.cs:
public class Startup
{
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyConfiguration>(options => {
options.SmtpServer = Configuration["SmtpServer"];
});
// ...
services.AddSingleton<IConfiguration>(Configuration);
}
}
Program.cs:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost
.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
config.AddEFConfiguration(options => options.UseNpgsql("connection_string"));
config.AddCommandLine(args);
})
.UseStartup<Startup>();
}
控制器:
public class TestController : ControllerBase
{
private readonly IConfigurationRoot _configurationRoot;
public TestController(IConfiguration configurationRoot)
{
_configurationRoot = (IConfigurationRoot)configurationRoot;
}
[HttpGet]
public async Task<IActionResult> Index()
{
// some logic for updating values in the database
// Doesn't work
_configurationRoot.Reload();
return Ok();
}
}