asp.net core 读取连接字符串

从类库中读取配置文件需要添加程序集:

  Install-Package Microsoft.Extensions.Configuration

  Install-Package Microsoft.Extensions.Configuration.Json

{
  "ConnectionStrings": {
    "Default": "Data Source = DESKTOP-A8O71KP\\MSSQLSERVER2017;Initial Catalog = test; User ID = sa;Password =123"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

 

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

namespace Common
{
    public class ConfigurationManager
    {
        public readonly static IConfiguration Configuration;
        static ConfigurationManager()
        {
       // Configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true) .Build(); } public static string conn { get {return Configuration.GetConnectionString("Default"); } } } }

参考:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.2

 

上一篇:.NET CORE编写控制台程序应有的优雅姿势(转载)


下一篇:.NET Core 发布部署问题