当前位置 : 主页 > 网络编程 > ASP >

ASP.NET Core Web读取appsettings.json中的配置

来源:互联网 收集:自由互联 发布时间:2021-06-24
1.Nuget添加Microsoft.Extensions.Configuration.Json 2.appsettings.json中添加"ConnectionStrings" { "Logging": { "LogLevel": { "Default": "Warning" } }, "ConnectionStrings": { "SQLConnection": "Data Source=127.0.0.1;Database=xxxx;UID=xx;P

1.Nuget添加Microsoft.Extensions.Configuration.Json

2.appsettings.json中添加"ConnectionStrings"

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
 "ConnectionStrings": { "SQLConnection": "Data Source=127.0.0.1;Database=xxxx;UID=xx;PWD=xx;", "OracleConnection": "", "MySqlConnection": "", "SqlLiteConnection": "" },
  "AllowedHosts": "*"
}

3.新建AppSettingsJson.cs

using Microsoft.Extensions.Configuration;
using System.IO;

namespace WebAPI
{
    public class AppSettingsJson
    {
        public static string ApplicationExeDirectory()
        {
            var location = System.Reflection.Assembly.GetExecutingAssembly().Location;
            var appRoot = Path.GetDirectoryName(location);
            return appRoot;
        }
        public static IConfigurationRoot GetAppSettings()
        {
            string applicationExeDirectory = ApplicationExeDirectory();
            var builder = new ConfigurationBuilder()
            .SetBasePath(applicationExeDirectory)
            .AddJsonFile("appsettings.json");

            return builder.Build();
        }
    }
}

4.C#调用

var config = AppSettingsJson.GetAppSettings();
var str = config.GetSection("ConnectionStrings:SQLConnection").Value;
网友评论