本篇解决WorkerService项目本地运行时可以获取到appsettings.json节点参数内容,发布到服务器后获取到的是空值。
解决方式有二选择喜欢的就好。
方式一:
配置文件如图
1.创建一个承载类ConfigString.cs
public class ConfigString
{
public static ConfigString configString = new ConfigString();
/// <summary>
/// 数据库连接字符串
/// </summary>
public string MySqlConnection { get; set; }
/// <summary>
/// 每日执行时间-24小时制
/// </summary>
public string RunTime { get; set; }
}
2.到Program给承载类绑定数据
.ConfigureServices((hostContext, services) =>
{
IConfiguration configuration = hostContext.Configuration;
ConfigString.configString.MySqlConnection = configuration.GetConnectionString("MySqlConnection");
ConfigString.configString.RunTime = configuration.GetSection("RunTime").Value;
services.AddHostedService<Worker>();
});
3.使用
var sqlConnection = ConfigString.configString.MySqlConnection
var runTime = ConfigString.configString.RunTime
方式二:
在其它文件读自定义字段如
1.上面的有的这里就不再表述了,
.ConfigureServices((hostContext, services) =>
{
List<string> strs = new List<string>() { "MySqlConnection", "RunTime" };
var res = getyaml(strs);
ConfigString.configString.MySqlConnection = res[0];
ConfigString.configString.RunTime = res[1];
services.AddHostedService<Worker>();
});
2.读取.yaml文件节点方法。
public static List<string> GetYaml(List<string> key)
{
try
{
var path = Directory.GetCurrentDirectory();
string filePath = path + "/yamlfile.yaml";
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader reader = new StreamReader(fs, System.Text.Encoding.Default);
var yaml = new YamlStream();
yaml.Load(reader);
var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;
List<string> resStr = new List<string>();
foreach (var item in key)
{
string str = mapping[item].ToString();
resstr.Add(str);
}
return resStr;
}
catch (Exception e)
{
throw;
}
}