溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

ASP.NET?CORE如何讀取json格式配置文件

發(fā)布時(shí)間:2022-03-14 09:08:23 來源:億速云 閱讀:687 作者:小新 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)ASP.NET CORE如何讀取json格式配置文件,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

    在.Net Framework中,配置文件一般采用的是XML格式的,.NET Framework提供了專門的ConfigurationManager來讀取配置文件的內(nèi)容,.net core中推薦使用json格式的配置文件,那么在.net core中該如何讀取json文件呢?

    一、在Startup類中讀取json配置文件

    1、使用Configuration直接讀取

    看下面的代碼:

    public IConfiguration Configuration { get; }

    Configuration屬性就是.net core中提供的用來讀取json文件。例如:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
    
                string option1 = $"option1 = {this.Configuration["Option1"]}";
                string option2 = $"option2 = {this.Configuration["Option2"]}";
                string suboption1 = $"suboption1 = {this.Configuration["subsection:suboption1"]}";
                // 讀取數(shù)組
                string name1 = $"Name={this.Configuration["student:0:Name"]} ";
                string age1 = $"Age= {this.Configuration["student:0:Age"]}";
                string name2 = $"Name={this.Configuration["student:1:Name"]}";
                string age2 = $"Age= {this.Configuration["student:1:Age"]}";
                // 輸出
                app.Run(c => c.Response.WriteAsync(option1+"\r\n"+option2+ "\r\n"+suboption1+ "\r\n"+name1+ "\r\n"+age1+ "\r\n"+name2+ "\r\n"+age2));
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseHsts();
                }
    
                app.UseHttpsRedirection();
                app.UseMvc();
    }

    結(jié)果:

    ASP.NET?CORE如何讀取json格式配置文件

    2、使用IOptions接口

    1、定義實(shí)體類
    public class MongodbHostOptions
    {
            /// <summary>
            /// 連接字符串
            /// </summary>
            public string Connection { get; set; }
            /// <summary>
            /// 庫
            /// </summary>
            public string DataBase { get; set; }
    
            public string Table { get; set; }
    }
    2、修改json文件

    在appsettings.json文件中添加MongodbHost節(jié)點(diǎn):

    {
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "option1": "value1_from_json",
      "option2": 2,
      "subsection": {
        "suboption1": "subvalue1_from_json"
      },
      "student": [
        {
          "Name": "Gandalf",
          "Age": "1000"
        },
        {
          "Name": "Harry",
          "Age": "17"
        }
      ],
      "AllowedHosts": "*",
      //MongoDb
      "MongodbHost": {
        "Connection": "mongodb://127.0.0.1:27017",
        "DataBase": "TemplateDb",
        "Table": "CDATemplateInfo"
      }
    }

    注意:

    MongodbHost里面的屬性名必須要和定義的實(shí)體類里面的屬性名稱一致。

    3、在StartUp類里面配置

    添加OptionConfigure方法綁定

    private void OptionConfigure(IServiceCollection services)
    {
          //MongodbHost信息
          services.Configure<MongodbHostOptions>(Configuration.GetSection("MongodbHost"));
    }

    在ConfigureServices方法中調(diào)用上面定義的方法:

    public void ConfigureServices(IServiceCollection services)
    {
         // 調(diào)用OptionConfigure方法
         OptionConfigure(services);           
         services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    在控制器中使用,代碼如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Options;
    
    namespace ReadJsonDemo.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class MongodbController : ControllerBase
        {
            private readonly MongodbHostOptions _mongodbHostOptions;
    
            /// <summary>
            /// 通過構(gòu)造函數(shù)注入
            /// </summary>
            /// <param name="mongodbHostOptions"></param>
            public MongodbController(IOptions<MongodbHostOptions> mongodbHostOptions)
            {
                _mongodbHostOptions = mongodbHostOptions.Value;
            }
    
            [HttpGet]
            public async Task Get()
            {
               await Response.WriteAsync("Connection:" + _mongodbHostOptions.Connection + "\r\nDataBase;" + _mongodbHostOptions.DataBase + "\r\nTable:" + _mongodbHostOptions.Table);
            }
        }
    }

    運(yùn)行結(jié)果:

    ASP.NET?CORE如何讀取json格式配置文件

    3、讀取自定義json文件

    在上面的例子中都是讀取的系統(tǒng)自帶的appsettings.json文件,那么該如何讀取我們自己定義的json文件呢?這里可以使用ConfigurationBuilder類。

    實(shí)例化類
    var builder = new ConfigurationBuilder();
     添加方式1
    builder.AddJsonFile("path", false, true);

     其中path表示json文件的路徑,包括路徑和文件名。

    添加方式2
    builder.Add(new JsonConfigurationSource {Path= "custom.json",Optional=false,ReloadOnChange=true }).Build()

    具體代碼如下:

    private void CustomOptionConfigure(IServiceCollection services)
    {
                IConfiguration _configuration;
                var builder = new ConfigurationBuilder();
                // 方式1
                //_configuration = builder.AddJsonFile("custom.json", false, true).Build();
                // 方式2
                _configuration = builder.Add(new JsonConfigurationSource {Path= "custom.json",Optional=false,ReloadOnChange=true }).Build();
                services.Configure<WebSiteOptions>(_configuration.GetSection("WebSiteConfig"));
    }

    ConfigureServices方法如下:

    public void ConfigureServices(IServiceCollection services)
    {
                // 調(diào)用OptionConfigure方法
                OptionConfigure(services);
                CustomOptionConfigure(services);
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    控制器代碼如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Options;
    
    namespace ReadJsonDemo.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class MongodbController : ControllerBase
        {
            private readonly MongodbHostOptions _mongodbHostOptions;
    
            private readonly WebSiteOptions _webSiteOptions;
    
            /// <summary>
            /// 通過構(gòu)造函數(shù)注入
            /// </summary>
            /// <param name="mongodbHostOptions"></param>
            public MongodbController(IOptions<MongodbHostOptions> mongodbHostOptions,IOptions<WebSiteOptions> webSiteOptions)
            {
                _mongodbHostOptions = mongodbHostOptions.Value;
                _webSiteOptions = webSiteOptions.Value;
            }
    
            [HttpGet]
            public async Task Get()
            {
               await Response.WriteAsync("Connection:" + _mongodbHostOptions.Connection + "\r\nDataBase;" + _mongodbHostOptions.DataBase + "\r\nTable:" + _mongodbHostOptions.Table);
                await Response.WriteAsync("\r\n");
                await Response.WriteAsync("WebSiteName:" + _webSiteOptions.WebSiteName + "\r\nWebSiteUrl;" + _webSiteOptions.WebSiteUrl);
            }
        }
    }

    二、在類庫中讀取json文件

    在上面的示例中都是直接在應(yīng)用程序中讀取的,那么如何在單獨(dú)的類庫中讀取json文件呢?看下面的示例代碼:

    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Options;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    
    namespace Common
    {
        public class JsonConfigHelper
        {
            public static T GetAppSettings<T>(string fileName, string key) where T : class, new()
            {
                // 獲取bin目錄路徑
                var directory = AppContext.BaseDirectory;
                directory = directory.Replace("\\", "/");
    
                var filePath = $"{directory}/{fileName}";
                if (!File.Exists(filePath))
                {
                    var length = directory.IndexOf("/bin");
                    filePath = $"{directory.Substring(0, length)}/{fileName}";
                }
    
                IConfiguration configuration;
                var builder = new ConfigurationBuilder();
                
                builder.AddJsonFile(filePath, false, true);
                configuration = builder.Build();
    
                var appconfig = new ServiceCollection()
                    .AddOptions()
                    .Configure<T>(configuration.GetSection(key))
                    .BuildServiceProvider()
                    .GetService<IOptions<T>>()
                    .Value;
    
                return appconfig;
            }
        }
    }

    注意:這里要添加如下幾個(gè)程序集,并且要注意添加的程序集的版本要和.net core web項(xiàng)目里面的程序集版本一致,否則會報(bào)版本沖突的錯誤

    • 1、Microsoft.Extensions.Configuration

    • 2、Microsoft.Extensions.configuration.json

    • 3、Microsoft.Extensions.Options

    • 4、Microsoft.Extensions.Options.ConfigurationExtensions

    • 5、Microsoft.Extensions.Options

    json文件如下:

    {
      "WebSiteConfig": {
        "WebSiteName": "CustomWebSite",
        "WebSiteUrl": "https:localhost:12345"
      },
      "DbConfig": {
        "DataSource": "127.0.0.1",
        "InitialCatalog": "MyDb",
        "UserId": "sa",
        "Password": "123456"
      }
    }

    DbHostOptions實(shí)體類定義如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace ReadJsonDemo
    {
        public class DbHostOptions
        {
            public string DataSource { get; set; }
    
            public string InitialCatalog { get; set; }
    
            public string UserId { get; set; }
    
            public string Password { get; set; }
        }
    }

    注意:這里的DbHostOptions實(shí)體類應(yīng)該建在單獨(dú)的類庫中,這里為了演示方便直接建在應(yīng)用程序中了。

    在控制器中調(diào)用:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Common;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Options;
    
    namespace ReadJsonDemo.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class MongodbController : ControllerBase
        {
            private readonly MongodbHostOptions _mongodbHostOptions;
    
            private readonly WebSiteOptions _webSiteOptions;
    
            /// <summary>
            /// 通過構(gòu)造函數(shù)注入
            /// </summary>
            /// <param name="mongodbHostOptions"></param>
            public MongodbController(IOptions<MongodbHostOptions> mongodbHostOptions,IOptions<WebSiteOptions> webSiteOptions)
            {
                _mongodbHostOptions = mongodbHostOptions.Value;
                _webSiteOptions = webSiteOptions.Value;
            }
    
            [HttpGet]
            public async Task Get()
            {
                DbHostOptions dbOptions = JsonConfigHelper.GetAppSettings<DbHostOptions>("custom.json", "DbConfig");
                await Response.WriteAsync("DataSource:" + dbOptions.DataSource + "\r\nInitialCatalog;" + dbOptions.InitialCatalog+ "\r\nUserId:"+dbOptions.UserId+ "\r\nPassword"+dbOptions.Password);
                await Response.WriteAsync("\r\n");
                await Response.WriteAsync("Connection:" + _mongodbHostOptions.Connection + "\r\nDataBase;" + _mongodbHostOptions.DataBase + "\r\nTable:" + _mongodbHostOptions.Table);
                await Response.WriteAsync("\r\n");
                await Response.WriteAsync("WebSiteName:" + _webSiteOptions.WebSiteName + "\r\nWebSiteUrl;" + _webSiteOptions.WebSiteUrl);           
            }
        }
    }

    運(yùn)行結(jié)果:

    ASP.NET?CORE如何讀取json格式配置文件

    關(guān)于“ASP.NET CORE如何讀取json格式配置文件”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI