访问链接文件配置文件 - 或者如何到达输出目录
Access linked files configuration files - or how to reach the output directory
我们有一个基本结构如下的sln
Sln
|--MyApp.Lib
| |-- LotsOfCode
|--MyApp.Web (old)
| |-- SetParameters.DEV.xml
| |-- SetParameters.TEST.xml
| |-- SetParameters.PROD.xml
|--MyApp.API (net core)
|-- appsettings.json
|-- SetParameters.DEV.xml
|-- SetParameters.TEST.xml (link)
|-- SetParameters.PROD.xml (link)
我们想在 API 项目中重用设置文件。我创建了一个可以读取 SetParameters
文件的自定义 ConfigurationProvider
,但是当我将文件添加为 link.[= 时,我无法将其读取到 运行 17=]
问题:当我将文件添加为 link(并设置 type=Content
)时,它被复制到输出目录,但我不能似乎想出了一个安全的方法来获取该文件。然后 IHostinEnvironment
似乎不知道什么是 Output
或 bin
目录。
有什么想法吗?
IHostingEnvironment
环境有WebRootPath
属性,可以这样读取本地文件:
using System.IO;
IHostingEnvironment _env;
var pathToFile = Path.Combine(_env.WebRootPath, "SetParameters.TEST.xml"));
var settings = File.ReadAllLines(pathToFile);
但是,在 ASP.NET Core
中,您有机会绑定您的设置 with ConfigurationBuilder
。在给定的文章中,可以看到 JSON
文件使用情况,但是,您也可以使用 AddXmlFile
。它将像:
var builder = new ConfigurationBuilder()
// set current output path as root
.SetBasePath(env.ContentRootPath)
// EnvironmentName can be DEV, TEST, PROD, etc
.AddXmlFile($"SetParameters.{env.EnvironmentName}.xml");
IConfigurationRoot configuration = builder.Build();
之后你可以像这样访问你的参数,给定你的样本 xml:
<parameters>
<settings>
<param1 name="Test" value="val" />
</settings>
</parameters>
// will be "val"
configuration["Parameters:param1:value"]
我找到了关于 legacy apps configuration in ASP.NET core. Other option, more object-oriented, is to bind your parameters to a model class 的精彩文章,如 MSDN 文章所述。
我们有一个基本结构如下的sln
Sln
|--MyApp.Lib
| |-- LotsOfCode
|--MyApp.Web (old)
| |-- SetParameters.DEV.xml
| |-- SetParameters.TEST.xml
| |-- SetParameters.PROD.xml
|--MyApp.API (net core)
|-- appsettings.json
|-- SetParameters.DEV.xml
|-- SetParameters.TEST.xml (link)
|-- SetParameters.PROD.xml (link)
我们想在 API 项目中重用设置文件。我创建了一个可以读取 SetParameters
文件的自定义 ConfigurationProvider
,但是当我将文件添加为 link.[= 时,我无法将其读取到 运行 17=]
问题:当我将文件添加为 link(并设置 type=Content
)时,它被复制到输出目录,但我不能似乎想出了一个安全的方法来获取该文件。然后 IHostinEnvironment
似乎不知道什么是 Output
或 bin
目录。
有什么想法吗?
IHostingEnvironment
环境有WebRootPath
属性,可以这样读取本地文件:
using System.IO;
IHostingEnvironment _env;
var pathToFile = Path.Combine(_env.WebRootPath, "SetParameters.TEST.xml"));
var settings = File.ReadAllLines(pathToFile);
但是,在 ASP.NET Core
中,您有机会绑定您的设置 with ConfigurationBuilder
。在给定的文章中,可以看到 JSON
文件使用情况,但是,您也可以使用 AddXmlFile
。它将像:
var builder = new ConfigurationBuilder()
// set current output path as root
.SetBasePath(env.ContentRootPath)
// EnvironmentName can be DEV, TEST, PROD, etc
.AddXmlFile($"SetParameters.{env.EnvironmentName}.xml");
IConfigurationRoot configuration = builder.Build();
之后你可以像这样访问你的参数,给定你的样本 xml:
<parameters>
<settings>
<param1 name="Test" value="val" />
</settings>
</parameters>
// will be "val"
configuration["Parameters:param1:value"]
我找到了关于 legacy apps configuration in ASP.NET core. Other option, more object-oriented, is to bind your parameters to a model class 的精彩文章,如 MSDN 文章所述。