ASP.NET Core Options 使用方法

@adens 8/28/2020 8:15:57 AM

在ASP.NET Core configuration中绑定模型

1.基本使用

1.1.在appsetting.json中新建绑定的字段

{
    "Value": {
    "ValStr1": "test",
    "ValInt2": 221
  }
}

1.2.声明模型

 public class ValueModel
    {
        public string ValStr1 { get; set; }
        public int ValInt2 { get; set; }
    }

1.3.在startup中注入options

 public void ConfigureServices(IServiceCollection services)
{
    services.Configure<ValueModel>(Configuration.GetSection("Value"));
    // other code...
}

1.4.调用方式

//例如controller中

 public class HomeController : Controller
    {
        IOptions<ValueModel> _options;
        public HomeController(IOptions<ValueModel> options
         )
        {
            _options = options;
        }

        public IActionResult Index()
        {
            return Ok(new {
                OptionsVal1 = _options.Value.ValStr1,
                OptionsVal2 = _options.Value.ValInt2,
   
            });
        }
}

1.5.显示结果

{"optionsVal1":"test","optionsVal2":221}

注意事项:IOptions每次更改配置需要重新启动运行

1.6 实时修改方法

使用 IOptionsSnapshot,IOptionsMonitor实时修改appsetting.json显示

public class HomeController : Controller
    {
	IOptions<ValueModel> _options;
        IOptionsSnapshot<ValueModel> _snapshotOptionsAccessor;
        IOptionsMonitor<ValueModel> _optionsDelegate;
        public HomeController(IOptions<ValueModel> options,
            IOptionsSnapshot<ValueModel> snapshotOptionsAccessor,
            IOptionsMonitor<ValueModel> optionsMonitor)
        {
            _options = options;
            _snapshotOptionsAccessor = snapshotOptionsAccessor;
            _optionsDelegate = optionsMonitor;

        }

        public IActionResult Index()
        {
            return Ok(new
            {
                OptionsVal1 = _options.Value.ValStr1,
                OptionsVal2 = _options.Value.ValInt2,
                _snapshotOptionsVal1 = _snapshotOptionsAccessor.Value.ValStr1,
                _snapshotOptionsVal2 = _snapshotOptionsAccessor.Value.ValInt2,
                DelegateOptionsVal1 = _optionsDelegate.CurrentValue.ValStr1,
                DelegateOptionsVal2 = _optionsDelegate.CurrentValue.ValInt2,

            });
        }
}

1.7.显示结果

1.第一次显示

{"optionsVal1":"test","optionsVal2":221,"_snapshotOptionsVal1":"test","_snapshotOptionsVal2":221,"delegateOptionsVal1":"test","delegateOptionsVal2":221}

2.修改appsettings.json的字段

{
  "Value": {
    "ValStr1": "after modify",
    "ValInt2": 123
  }
}

3.修改后刷新页面.不重启

{"optionsVal1":"test","optionsVal2":221,"_snapshotOptionsVal1":"after modify","_snapshotOptionsVal2":123,"delegateOptionsVal1":"after modify","delegateOptionsVal2":123}

2.三种Options的区别

IOptions只会在初次启动时绑定字段数据,生命周期类型是Singleton IOptionsSnapshot会在每次请求时重新计算绑定的值,生命周期类型是Scoped,不能注入到singleton的生命周期的服务中

IOptionsMonitor会在模型绑定的字段改变后获得通知,每次请求都会使用最新的值.生命周期类型是Singleton可以注入到任何生命周期中

可以监听OnChnege事件执行委托方法

  _optionsDelegate.OnChange((listen) =>
            {
                Console.WriteLine("val1:{0},val2:{1}", listen.ValStr1, listen.ValInt2);
            });

3.代码修改config并重新加载

3.1.新建config.json并在Program中启用

1.新建config.json

{
  "Data": {
    "ID": "123123",
    "Name": "新的测试用例"
  }
}

2.加载到configuration中

 public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
		    webBuilder.ConfigureAppConfiguration((hostingContext, option) => {
                        option.AddJsonFile("config.json", true, true)
                        .AddJsonFile($"config.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true);
                    });
                    webBuilder.UseStartup<Startup>();
                });

3.2创建页面输入显示数据

//Config.cshtml
@model DataModel 


<form asp-action="Submit">
    <input asp-for="@Model.ID" />
    <input asp-for="@Model.Name" />
    <button type="submit">submit</button>
</form>

controller方法

 IOptionsMonitor<DataModel>  _data;

        public HomeController(IOptionsMonitor<DataModel> data,
            )
        {
     
            _data =data; 
        } 
public IActionResult Config()
        {
            return View("Config", _data.CurrentValue);
        }
        public IActionResult Submit( DataModel data)
        {

            using (FileStream fs = new FileStream(Directory.GetCurrentDirectory()+"/config.json",FileMode.Create, FileAccess.ReadWrite))
            {
      
                string str= "{\"Data\":{\"ID\":\""+data.ID+"\",\"Name\":\""+data.Name+"\"}}";
                byte[] bytes = Encoding.UTF8.GetBytes(str.ToString());
                fs.Write(bytes);
            }
                return Redirect("Config");
        }

3.3 结果展示

在/Home/Config中显示修改提交后会直接显示修改后的值.

3.4注意事项

1.不要使用 IOptionsIOptionsSnapshot

使用 IOptions不会自动更新数据

使用 IOptionsSnapshot在修改后的同一个请求中不会更新数据,即需要刷新页面之后才会展示,而提交之后重定向属于同一请求数据,数据不会改变

2.在AddJsonFile的参数需要设置reloadOnChanges = true

4.用途

用于在程序运行时修改配置.做到不停机修改配置

5.文件地址

示例文件地址

Last Modification : 8/28/2020 8:15:57 AM


In This Document