在.net core Mvc中使用Options

1.Startup.cs 下代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;

namespace OptionsBindSample
{
    public class Startup
    {
        /// <summary>
        /// 添加构造方法用来获取配置信息
        /// </summary>
        public IConfiguration Configuration { get; set; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            //把配置信息注入到Configure中
            services.Configure<Class>(Configuration);
            //添加MVC,依赖注入的配置
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            //启动默认路由
            app.UseMvcWithDefaultRoute();

            //app.Run(async (context) =>
            //{
            //    var myClass = new Class();
            //    Configuration.Bind(myClass);//绑定基础信息
            //    //输出json配置到页面
            //    await context.Response.WriteAsync($"ClassNo {myClass.ClassNo}");
            //    await context.Response.WriteAsync($"ClassDesc {myClass.ClassDesc}");
            //    await context.Response.WriteAsync($"myClass Count {myClass.Students.Count}");
            //});
        }
    }
}
2.创建HomeController添加以下代码
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace OptionsBindSample.Controllers
{
    public class HomeController : Controller
    {
        private readonly Class _myClass;
        public HomeController(IOptions<Class> options)
        {
            _myClass = options.Value;
        }

        public IActionResult Index()
        {
            return View(_myClass);
        }
    }
}
3.视图层展示参数
@model OptionsBindSample.Class
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h3>Class No: @Model.ClassNo</h3>
    <h3>ClassDesc: @Model.ClassDesc</h3>
    <div>
        @foreach (var item in Model.Students)
        {
            <span>Name:@item.Name</span>
            <span>Name:@item.Age</span>
        }
    </div>
</body>
</html>
页面直接通过依赖注入读取配置信息
@using Microsoft.Extensions.Options;
@*@model OptionsBindSample.Class*@

@inject IOptions< OptionsBindSample.Class> MyClass

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h3>Class No: @MyClass.Value.ClassNo</h3>
    <h3>ClassDesc: @MyClass.Value.ClassDesc</h3>
    <div>
        @foreach (var item in MyClass.Value.Students)
        {
            <span>Name:@item.Name</span>
            <span>Name:@item.Age</span>
        }
    </div>
</body>
</html>
5.Class 实体类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OptionsBindSample
{
    public class Class
    {
        public int ClassNo { get; set; }
        public string ClassDesc { get; set; }
        public List<Student> Students { get; set; }
    }

    public class Student
    {
        public string Name { get; set; }
        public string Age { get; set; }
    }
}
6.json文件命名为 appsettings.json
{
  "ClassNo": "1",
  "ClassDesc": "ASP.NET Core 101",
  "Students": [
    {
      "name": "name1",
      "age": "12"
    },
    {
      "name": "name2",
      "age": "13"
    },
    {
      "name": "name13",
      "age": "14"
    }
  ]
}
 7. 配置的热更新(解决了不需要重启网站及时读取配置信息的时候可以使用)@inject IOptionsSnapshot MyClass
@using Microsoft.Extensions.Options;
@using OptionBindSample
@*@model OptionsBindSample.Class*@

@inject IOptionsSnapshot<Class> MyClass

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
<h3>Class No: @MyClass.Value.ClassNo</h3>
<h3>ClassDesc: @MyClass.Value.ClassDesc</h3>
<div>
    @foreach (var item in MyClass.Value.Students)
    {
        <span>Name:@item.Name</span>
        <span>Name:@item.Age</span>
    }
</div>
</body>
</html>
 

相关内容推荐