public class HomeController : Controller
{
//环境变量
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"];
}
}</code></pre>
- 第二种是通过获取对象的方式读取配置文件,最近很多博客说的都是关于这个的。还是在controller初始化的时候把IOptions传进来(这里我还是没懂怎么传过来的/(ㄒoㄒ)/~~),然后把传过来的值赋值给Model的对象,然后就可以正常使用了。
这种方法需要在StartUp中的ConfigureServices中有添加
services.AddOptions();
//SettingPath极为Model
services.Configure(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
}
}
这里因为我不了解,IOptions是怎么传进来的,所以不知道如果有需要只用两个或以上Model的情况该怎么处理。
前面几种方法之前都有用过,但是个人感觉用起来都不是很顺手。而且如果想要在一个类库中读取配置文件的话简直痛苦到不想理媳妇。
所以自己动手写了一个工具类
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();
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(string key) where T : class,new()
{
var appconfig = new ServiceCollection()
.AddOptions()
.Configure(config.GetSection(key))
.BuildServiceProvider()
.GetService<IOptions>()
.Value;
return appconfig;
}
}
//我比较喜欢单独放这个类,但是这样放更明显
public class MyServiceProvider
{
public static IServiceProvider ServiceProvider { get; set; }
}
}
使用这个类的话需要在StartUp的Configure中添加
MyServiceProvider.ServiceProvider = app.ApplicationServices;
然后就可以在任何地方使用此类读取配置文件信息了,而且由于ConfigurationHelper初始化时已经默认加载环境变量,所以同时具备多环境功能。
string path = new ConfigurationHelper().config["RedisPath"];
SettingPath pathss = new ConfigurationHelper().GetAppSettings("SettingPath");
参考
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!