(十三)在ASP.NET CORE中使用Options
- 这一节介绍Options方法,继续在OptionsBindSample项目下。
- 在项目中添加一个Controllers文件夹,文件夹添加一个HomeController控制器
- HomeController.cs
-
1 private readonly Class _myClass; 2 3 public HomeController(IOptions<Class> classAccesser)//IOptions的方法注入 4 { 5 this._myClass = classAccesser.Value; 6 } 7 8 public IActionResult Index() 9 { 10 return View(_myClass); 11 }
- 在项目中添加一个Views文件夹,文件夹中添加一个Home文件夹(这和ASP.NET MVC一样),Home文件夹下添加一个Index.cshtml
-
1 @model OptionsBindSample.Class 2 3 @{ 4 ViewData["Title"] = "Index"; 5 } 6 7 <h2>Index</h2> 8 9 <div> 10 @foreach(var stu in Model.Students) 11 { 12 <span>Name:@stu.Name</span> 13 <span>Age:@stu.Age</span> 14 15 } 16 </div>
- 此时StartUp.cs应该改成这样
-
1 public IConfiguration Configuration { get; set; } 2 3 public Startup(IConfiguration configuration) 4 { 5 this.Configuration = configuration; 6 } 7 8 // This method gets called by the runtime. Use this method to add services to the container. 9 // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 10 public void ConfigureServices(IServiceCollection services) 11 { 12 services.Configure<Class>(Configuration); 13 14 services.AddMvc(); 15 } 16 17 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 18 public void Configure(IApplicationBuilder app, IHostingEnvironment env) 19 { 20 if (env.IsDevelopment()) 21 { 22 app.UseDeveloperExceptionPage(); 23 } 24 25 app.UseMvcWithDefaultRoute(); 26 }
也可以不用在Controller中依赖注入,而在视图中注入,改成如下:
HomeController.cs
1 public IActionResult Index() 2 {
3 return View(); 4 }
Index.cshtml:
1 @using Microsoft.Extensions.Options 2 @inject IOptions<OptionsBindSample.Class> ClassAccesser 3 @{ 4 ViewData["Title"] = "Index"; 5 } 6 <h2>Index</h2> 7 8 <div> 9 @foreach(var stu in ClassAccesser.Value.Students) 10 { 11 <span>Name:@stu.Name</span> 12 <span>Age:@stu.Age</span> 13 14 } 15 </div>