一:读取配置文件

先来看一下appsettings.json文件的内容,如下图:

{
  "ConnectionStrings": {
    "ServerConnection": "Data Source=users.db;",
    "BaseWebContext": "Server=.; database=BaseWebApp;uid=sa;pwd=@sa123;",
    "RedisConnection": "127.0.0.1:6380,password=123"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "Redis": {
    "ConnectionString": "127.0.0.1:6380,password=123"
  },
  "MongoDB": {
    "ConnectionString": "mongodb://127.0.0.1"
  },
  "AllowedHosts": "*",
  "Url": "http://*:8088"
}

接下来主要是实现如何获取ConnectionStrings和Redis节点下面的链接字符串信息

1.新建ConfigurationManager.cs管理类

 

 

 

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace GyouApi
{
    public static class ConfigurationManager
    {
        public readonly static IConfiguration Configuration;

        static ConfigurationManager()
        {
            Configuration = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
               .Build();
        }

        public static T GetSection<T>(string key) where T : class, new()
        {
            return new ServiceCollection()
                .AddOptions()
                .Configure<T>(Configuration.GetSection(key))
                .BuildServiceProvider()
                .GetService<IOptions<T>>()
                .Value;
        }

        public static string GetSection(string key)
        {
            return Configuration.GetValue<string>(key);
        }
    }
}

2.获取ConnectionStrings节点下面的配置

分别获取BaseWebContext 和RedisConnection

private static readonly string BaseWebContextString = ConfigurationManager.Configuration.GetConnectionString("BaseWebContext")

private static readonly string RedisConnectionString = ConfigurationManager.Configuration.GetConnectionString("RedisConnection");

3.获取Redis节点下面的配置

 获取Redis的ConnectionString,  MongoDB下的同理


//Redis节点
private static readonly string RedisConnectionStringR = ConfigurationManager.GetSection("Redis:ConnectionString");
//ConnectionString节点
private static readonly string RedisConnectionString = ConfigurationManager.Configuration.GetConnectionString("RedisConnection");

 

posted on 2020-09-14 15:25  JioNote  阅读(149)  评论(0编辑  收藏  举报