.Net Core讀取Json配置文件的實現(xiàn)示例
前言:在與傳統(tǒng)的asp.net MVC項目相比,.net core項目在項目目錄的文件結(jié)構(gòu)上和功能上與前者都有很大的區(qū)別。例如:在.net core中使用Startup.cs取代Global.asax文件用于加載應(yīng)用程序的配置和各種啟動項。appsettings.json取代web.config文件用于存儲應(yīng)用程序所需的配置參數(shù)等等。。。
OK!步入正題,下面來說一下如何讀取Json配置文件中的參數(shù)。
第一種:使用IConfiguration接口
我們先在appsettings.json中配置好數(shù)據(jù)庫連接字符串,然后讀取它
{
"Connection": {
"dbContent": "Data Source=.;Initial Catalog=test;User ID=sa;Password=123456"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}

在控制器中注入IConfiguration接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
namespace Read.json.Controllers
{
[ApiController]
[Route("[controller]")]
public class ReadController : Controller
{
private IConfiguration _configuration;
public ReadController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpPost]
public async Task<string> ReadJson()
{
//讀參
string conn = _configuration["Connection:dbContent"];
return "";
}
}
}

當(dāng)然也可以讀取數(shù)組形式的json,一樣的先在appsettings.json中寫好配置參數(shù),如下:
{
"Connection": {
"dbContent": "Data Source=.;Initial Catalog=test;User ID=sa;Password=123456"
},
//------------------------
"Content": [
{
"Trade_name": {
"test1": "小熊餅干",
"test2": "旺仔QQ糖",
"test3": "娃哈哈牛奶"
}
}
],
//------------------------
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
比如我們想讀取test1
string commodity_test1 = _configuration["Content:0:Trade_name:test1"];
第二種:使用IOptions<T>來讀取json配置文件
先把NuGet包導(dǎo)進(jìn)項目:Microsoft.Extensions.Options.ConfigurationExtensions

首先在appsettings.json中添加節(jié)點如下
{
"Connection": {
"dbContent": "Data Source=.;Initial Catalog=test;User ID=sa;Password=123456"
},
//------------------------
"Content": [
{
"Trade_name": {
"test1": "小熊餅干",
"test2": "旺仔QQ糖",
"test3": "娃哈哈牛奶"
}
}
],
//------------------------
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
//==============================
"Information": {
"school": {
"Introduce": {
"Name": "實驗小學(xué)",
"Class": "中班",
"Number": "15人"
},
"Region": {
"Province": "湖北",
"City": "武漢",
"Area": "洪山區(qū)"
},
"Detailed_address": [
{
"Address": "佳園路207號"
}
]
}
}
//==============================
}
然和再建立一個與這個節(jié)點"相同"的類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Read.json
{
public class Information
{
public School school { get; set; }
}
public class School
{
public Introduce Introduce { get; set; }
public Region Region { get; set; }
public List<Detailed_address> data { get; set; }
}
public class Introduce
{
public string Name { get; set; }
public string Class { get; set; }
public string Number { get; set; }
}
public class Region
{
public string Province { get; set; }
public string City { get; set; }
public string Area { get; set; }
}
public class Detailed_address
{
public string Address { get; set; }
}
}
在Startup中添加如下代碼
#region 服務(wù)注冊,在控制器中通過注入的形式使用
services.AddOptions();
services.Configure<Information>(Configuration.GetSection("Information"));
#endregion

控制器中使用:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
namespace Read.json.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ReadController : Controller
{
private IConfiguration _configuration;
readonly Information _Information;
readonly IOptions<Information> _options;
public ReadController(IConfiguration configuration,
Information Information,
IOptions<Information> options)
{
_configuration = configuration;
_Information = Information;
_options = options;
}
[HttpGet]
public async Task<IActionResult> ReadInformation()
{
string Address = _options.Value.school.Region.Province + "-" +
_options.Value.school.Region.City + "-" +
_options.Value.school.Region.Area + "-" +
_options.Value.school.Detailed_address[0].Address + "-" +
_options.Value.school.Introduce.Name + "-" +
_options.Value.school.Introduce.Class + "-" +
_options.Value.school.Introduce.Number;
return Json(Address);
}
[HttpPost]
public async Task<string> ReadJson()
{
string conn = _configuration["Connection:dbContent"];
string commodity = _configuration["Content:0:Trade_name:test1"];
return "";
}
}
}


第三種:這種應(yīng)該比較常見,任意讀取自定義的json文件
首先建立一個json文件
{
"system_version": {
"Edition": ".Net Core 3.0",
"Project_Name": "Read.json"
}
}

再建一個類,封裝一個方法
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Read.json
{
public class Json_File
{
public IConfigurationRoot Read_Json_File()
{
//這句代碼會讀取read_json.json中的內(nèi)容
return new ConfigurationBuilder().AddJsonFile("read_json.json")
.Build();
}
}
}

在控制器中調(diào)用:
[HttpGet]
public async Task<IActionResult> ReadSystemVersion()
{
var configuration = _json_File.Read_Json_File();
string system = "使用的是" + configuration["system_version:Edition"] + "的版本" + "," +
"項目名稱是" + configuration["system_version:Project_Name"];
return Json(new
{
data = system
});
}


Demo地址:https://github.com/Davenever/Read_Json.git
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
asp.net 使用駐留在頁面中的Cache緩存常用可定時更新的數(shù)據(jù)
這個就先需要先知道一下System.Web.Caching.Cache類,其實在我做WEB應(yīng)用的時候,我會將一些使用頻繁但是又要經(jīng)常使用并且需要急時更新的對象放到Cache中,這樣可以很大程序上減少從硬盤上讀取數(shù)據(jù)的次數(shù)。2010-03-03
asp.net動態(tài)獲取Excel表名的函數(shù)代碼
asp.net動態(tài)獲取Excel表名的函數(shù)代碼,需要的朋友可以參考下。2011-02-02
asp.net core 2.0 webapi集成signalr(實例講解)
下面小編就為大家分享一篇asp.net core 2.0 webapi集成signalr的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-11-11
ASP.net在頁面所有內(nèi)容生成后、輸出內(nèi)容前對頁面內(nèi)容進(jìn)行操作
ASP.net在頁面所有內(nèi)容生成后、輸出內(nèi)容前對頁面內(nèi)容進(jìn)行操作...2007-04-04
.net indexOf(String.indexOf 方法)
字符串的IndexOf()方法搜索在該字符串上是否出現(xiàn)了作為參數(shù)傳遞的字符串,如果找到字符串,則返回字符的起始位置 (0表示第一個字符,1表示第二個字符依此類推)如果說沒有找到則返回 -12012-10-10

