• ASP.NET Core MVC创建并关联JSON配置文件


    1.目录下创建 appsettings.json文件


    内容:

    {
        "ConnectionStrings": {
            "DefaultConnection": "Databases = InMemory;",
            "Myname": "Lihuahua;"
        }
    }
    
    

    2.创建Settings文件夹下,新增类

    类具体内容:(属性的名字和appsettings.json文件中键值对的键相对应)

    namespace TestMvc.Settings
    {
        public class ConnectionStringOptions
        {
            public string DefaultConnection { get; set; }
            public string Myname { get; set; }
        }
    }
    
    

    3.在Startup方法中注册服务

    
            //Startup中添加    
            //构造方法
            private readonly IConfiguration _configuration;
            public Startup(IConfiguration configuration)
            {
                _configuration = configuration;
            }
    

    ConfigureServices方法中关联服务

            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc();//使用该方法后才可以使用app.UseMvc()方法
                services.AddSingleton<Ifactory, Factory>();
                //关联起来
                services.Configure<ConnectionStringOptions>(_configuration.GetSection("ConnectionStrings"));
            }
    

    4.引用
    csHtml中引用

    @using Microsoft.Extensions.Options;
    @inject IOptions<TestMvc.Settings.ConnectionStringOptions> ioption;
    <div class="jumbotron">
        <h1 class="display-4"> @ioption.Value.Myname</h1>
    </div>
    

    后台引用

        public class HomeController:Controller 
        {
            //构造方法中初始化值
            private IOptions<ConnectionStringOptions> option;
            public HomeController(IOptions<ConnectionStringOptions> options)
            {
                this.option = options;
            }
         }
    

    PS:

            public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((context,builder)=> { 
                builder.//这里选择添加配置文件的格式
                })
                    .UseStartup<Startup>();
    
  • 相关阅读:
    Leetcode 449. Serialize and Deserialize BST
    机器学习入门(1)------python基础
    Leetcode 23. Merge k Sorted Lists
    mysql explain执行计划详解
    ubuntu下安装chrome浏览器证书
    ubantu下配置android开发环境(Ubuntu 12.04.4 LTS x64 dell 3420)
    system v信号量的深入剖析
    AI文件格式解析
    STC12LE5A60S2第二串口出现的奇葩问题
    ZIGBEE官方协议栈 SampleApp工程DemoEB项目 运行机制详解
  • 原文地址:https://www.cnblogs.com/liflower/p/13888522.html
Copyright © 2020-2023  润新知