按部就班學.Net Core Web Api開發系列【6】:配置文件appsettings.json

系列目錄html

按部就班學.Net Core Web Api開發系列目錄git

 本系列涉及到的源碼下載地址:https://github.com/seabluescn/Blog_WebApigithub

 

1、本篇概述json

 本篇描述appsettings.json的使用,包括:app

一、配置的基本讀取ui

二、讀取配置信息到自定義的對象this

三、自定義配置文件spa

 

1、配置的基本讀取code

 要讀取的配置文件內容以下:htm

{
  "ConnString": "MySQL Connect String",
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "SystemConfig": {
    "UploadFile": "d:\\files",
    "AnnexUrl": "http://192.168.0.177:81/",
    "Admin": {
      "Name": "admin",
      "Age": "31",
      "Allow": "True"
    },
    "DefaultPassword": "123456"
  }
}

讀取配置文件的方法以下:

   public class Startup
    {
        public Startup(IConfiguration configuration,IHostingEnvironment env)
        {
            Configuration = configuration;
            _env = env;
        }

        public IConfiguration Configuration { get; }
        public IHostingEnvironment _env { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

var ConnString = Configuration["ConnString"]; var UploadFile = Configuration.GetSection("SystemConfig")["UploadFile"]; var AdminName = Configuration.GetSection("SystemConfig").GetSection("Admin")["Name"];
} }

還有一種讀法:

            ConnString = Configuration["ConnString"];  
            UploadFile = Configuration["SystemConfig:UploadFile"];           
            AdminName = Configuration["SystemConfig:Admin:Name"];           

這裏Startup類在構造時已經幫咱們注入了Configuration,若是要在本身的Controller內使用,須要本身注入。

    public class ValuesController : Controller
    {
        private IConfiguration _configuration;

        public ValuesController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [HttpGet]
        public IEnumerable<string> Get()
        {
            var ConnString = _configuration["ConnString"]; 
            return new string[] { "value1", "value2" };
        }
    }

 

2、讀取配置信息到自定義的對象

 新建一個類,用來存儲配置信息,類的結構應和配置文件一致。

    public class SystemConfig
    {
        public String UploadFile { get; set; }       
        public String AnnexUrl { get; set; }
        public User Admin { get; set; }
        public String DefaultPassword { get; set; }
    }

    public class User
    {
        public String Name { get; set; }
        public int Age { get; set; }
        public bool Allow { get; set; }
    }

在startup類的ConfigureServices方法內,提供以下代碼:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;           
        }

        public IConfiguration Configuration { get; }
      
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddOptions();
            services.Configure<SystemConfig>(Configuration.GetSection("SystemConfig"));  
        }      
    }
}

而後在Controller中進行注入並使用。

    public class ValuesController : Controller
    {
        private IOptions<SystemConfig> _setting;

        public ValuesController(  IOptions<SystemConfig> setting)
        {
                   _setting = setting;
        }      

        [HttpGet("setting")]
        public IEnumerable<string> GetSetting()
        {
            var UploadFile = _setting.Value.UploadFile;
            var AdminName = _setting.Value.Admin.Name;
            var AdminAge = _setting.Value.Admin.Age;
            var AdminAllow = _setting.Value.Admin.Allow;

            return new string[] { "value1", "value2" };
        }
    }

能夠看到,這樣在業務方法內經過 _setting 來都取配置信息就很是方便了。

 

3、自定義配置文件

 以上操做的是系統默認的配置文件appsettings.json。若是咱們須要增長本身的配置文件該如何處理?

新建一個配置文件:mysetting.json

{
  "ConnString": "MySQL Connect String",  
  "SystemConfig": {
    "UploadFile": "d:\\myfiles",
    "AnnexUrl": "http://192.168.0.177:81/my",
    "Admin": {
      "Name": "myadmin",
      "Age": "131",
      "Allow": "False"
    },
    "DefaultPassword": "654321"
  }
}

在Startup類的ConfigureServices方法輸入如下代碼:

    public class Startup
    {
        public Startup(IConfiguration configuration,IHostingEnvironment env)
        {
            Configuration = configuration;
            _env = env;
        }

        public IConfiguration Configuration { get; }
        public IHostingEnvironment _env { get; }
       
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
          
            var rootpath = _env.ContentRootPath;           
            var builder = new ConfigurationBuilder()
               .SetBasePath(_env.ContentRootPath)
               .AddJsonFile("mysetting.json",optional: true, reloadOnChange: true)
               .AddEnvironmentVariables();
            var MyConfiguration = builder.Build();

            services.AddOptions();
            services.Configure<SystemConfig>(MyConfiguration.GetSection("SystemConfig"));
        }
    }

用本身建立的Configuration進行服務的註冊,建立過程當中須要用到IHostingEnvironment,這個對象在Startup類構建時進行注入。

剩下的用法和默認配置用法就同樣了。

相關文章
相關標籤/搜索