Asp.net core中实现自动更新的Option的方法示例

2019-05-25 07:57:53于海丽

WebHost.CreateDefaultBuilder(args)
  .ConfigureAppConfiguration(config =>
  {
    config.AddAutoRereshConfiguration();
  })
  .UseStartup<Startup>();

在Startup. ConfigureServices中配置

services.Configure<RefreshableOptions>(Configuration.GetSection("AutoRefreshOptions"));

修改ValuesController

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
  private RefreshableOptions refreshableOptions;
  public ValuesController(IOptionsSnapshot<RefreshableOptions> refreshableOptions)
  {
    this.refreshableOptions = refreshableOptions.Value;
  }

  [HttpGet]
  public ActionResult<IEnumerable<string>> Get()
  {
    return new string[] { "value1", "value2", refreshableOptions.IncreasementCount.ToString() };
  }
}

启动后不停的刷新http://localhost:5000/api/values可以看到返回内容的变化

本文代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。