.Net Core如何讀取Json設定檔

angryTom
發布: 2019-11-27 14:56:40
轉載
4201 人瀏覽過

前言:在與傳統的asp.net MVC專案相比,.net core專案在專案目錄的檔案結構上和功能上與前者都有很大的區別。例如:在.net core中使用Startup.cs取代Global.asax檔案用於載入應用程式的設定和各種啟動項目。 appsettings.json取代web.config檔案用於儲存應用程式所需的設定參數等等。 。 。

.Net Core如何讀取Json設定檔

OK!步入正題,下面來說一下如何讀取Json設定檔中的參數。

第一種:使用IConfiguration介面

我們先在appsettings.json中設定好資料庫連接字串,然後讀取它

{
  "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 "";
        }

    }
}</string>
登入後複製

 當然也可以讀取數組形式的json,一樣的先在appsettings.json中寫好設定參數,如下:

{
  "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來讀取json設定檔

先把NuGet套件導進專案:Microsoft.Extensions.Options.ConfigurationExtensions

.Net Core如何讀取Json設定檔

{
  "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": "实验小学",
        "Class": "中班",
        "Number": "15人"
      },
      "Region": {
        "Province": "湖北",
        "City": "武汉",
        "Area": "洪山区"
      },
      "Detailed_address": [
        {
          "Address": "佳园路207号"
        }
      ]
    }
  }
  //==============================
}
登入後複製
登入後複製
# 在Startup中加入如下程式碼

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; }
    }
}</detailed_address>
登入後複製

 控制器中使用:

            #region 服务注册,在控制器中通过注入的形式使用
            services.AddOptions();
            services.Configure<information>(Configuration.GetSection("Information"));            #endregion</information>
登入後複製

 

#第三種:這種應該比較常見,任意讀取自訂的json檔案

先建立一個json檔案

{
  "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": "实验小学",
        "Class": "中班",
        "Number": "15人"
      },
      "Region": {
        "Province": "湖北",
        "City": "武汉",
        "Area": "洪山区"
      },
      "Detailed_address": [
        {
          "Address": "佳园路207号"
        }
      ]
    }
  }
  //==============================
}
登入後複製
登入後複製

#再建立一個類別,封裝一個方法

{
  "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中的内容
            return new ConfigurationBuilder().AddJsonFile("read_json.json")
                                             .Build();

        }

    }
}
登入後複製
 

## 本文來自

C#.Net教學

欄目,歡迎學習!  

以上是.Net Core如何讀取Json設定檔的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:cnblogs.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!