Asp. net Core and Class Library Read Configuration File Information Method

  • 2021-10-27 07:07:19
  • OfStack

Preface

First of all, open a brain hole. Asp. net core has been used for so long, but Microsoft officials do not seem to give reading configuration files (json) as simple and perfect as reading web. config by net framework. It is seriously suspected that this is a small means for Microsoft to promote the ecological prosperity of. net core.

appsetting. Development. json (appsetting. json is similar to this, and we will talk about multi-environment use below)


{
 "SettingPath": {
 "VideoFilePath": "C:\\Users\\89275\\Desktop\\Projects\\mv",
 "FfmpegPath": "C:/Users/89275/Desktop/Projects/mv/ffmpeg.exe",
 "FtpPath": "http://192.168.254.1/videofile",
 "VirtualPath": "/videoplay"
 },
 "RedisPath":"192.168.0.108:6379"
}

Read a lot of Asp. net core reading configuration files blog, feeling is not a good solution to the problem.

The simplest is to get information in the form of Configuration ["SettingPath: VirtualPath"] in StartUp; The next step is to get the configuration file information in Controller. There are two ways to read the configuration file in the controller.

The first one is to pass IHostingEnvironment and IConfiguration when controller is initialized, and then assign the values to the corresponding variables in controller, so that the configuration file can be read normally after drinking (because I am a vegetable force, I haven't seen how these two variables are passed to controller when the system starts)


  public class HomeController : Controller
 {
  // Environment variable 
  private readonly IHostingEnvironment hostingEnvironment;
  private IConfiguration Configuration;
  public HomeController(IHostingEnvironment hostingEnvironment, IConfiguration configuration)
  {
   this.hostingEnvironment = hostingEnvironment;
   Configuration = configuration;
  }

  pubilc void GetRedisPath()
  {
   string redisPath = Configuration["RedisPath"];
  }
 }

The second is to read the configuration file by fetching objects, which has been talked about by many blogs recently. Send IOptions in when controller is initialized (I still don't know how to send it here/(ubiquitous o)/~ ~), and then assign the passed value to the object of Model, and then it can be used normally.

This method needs to be added in ConfigureServices in StartUp


   services.AddOptions();
   //SettingPath Extremely Model
   services.Configure<SettingPath>(Configuration.GetSection("SettingPath"));

 public class HomeController
 {

  public SettingPath settingPath;
  private ILog log = LogManager.GetLogger(Startup.repository.Name, typeof(VideosController));
  public HomeController(IOptions<SettingPath> option)
  {
   settingPath = option.Value;
  }

  public void GetVideoPath()
  {
   string path=SettingPath.VideoFilePath
  }
 }

Here, because I don't know how IOptions came in, I don't know what to do if I need to use only two or more Model.

net core Read Configuration File Public Class

The previous methods have been used before, but I feel that they are not very convenient to use. Moreover, if you want to read the configuration file in a class library, it is so painful that you don't want to manage your daughter-in-law.

So I wrote a tool class by myself


using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using System;

namespace Common
{
 public class ConfigurationHelper
 {
  public IConfiguration config { get; set; }
  public ConfigurationHelper()
  {
   IHostingEnvironment env = MyServiceProvider.ServiceProvider.GetRequiredService<IHostingEnvironment>();
   config = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
    .AddEnvironmentVariables()
    .Build();
  }
  public T GetAppSettings<T>(string key) where T : class, new()
  {
   var appconfig = new ServiceCollection()
    .AddOptions()
    .Configure<T>(config.GetSection(key))
    .BuildServiceProvider()
    .GetService<IOptions<T>>()
    .Value;
   return appconfig;
  }
 }
 // I prefer to put this class alone, but it is more obvious to put it this way 
 public class MyServiceProvider
 {
  public static IServiceProvider ServiceProvider { get; set; }
 }
}

If you use this class, you need to add it in Configure of StartUp


 MyServiceProvider.ServiceProvider = app.ApplicationServices;

This class can then be used anywhere to read configuration file information, and since ConfigurationHelper has already loaded environment variables by default when initialized, it has multi-environment functionality at the same time.


 string path = new ConfigurationHelper().config["RedisPath"];
   SettingPath pathss = new ConfigurationHelper().GetAppSettings<SettingPath>("SettingPath");

Reference

https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1 https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/environments?view=aspnetcore-2.1 https://www.ofstack.com/article/125674.htm

Summarize


Related articles: