本文介绍了如何在.NET Core中使用.settings文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将应用程序移植到依赖.settings文件的.NET Core.不幸的是,我找不到从.NET核心读取它的方法.通常,将以下行添加到.csproj会生成一个TestSettings类,该类可以让我读取设置.

I'm porting an application to .NET core which relies on a .settings file. Unfortunately, I can't find a way to read it from .NET core. Normally, adding the following lines to the .csproj would generate a TestSettings class that would let me read the settings.

<ItemGroup>
    <None Include="TestSettings.settings">
        <Generator>SettingsSingleFileGenerator</Generator>
    </None>
</ItemGroup>

不幸的是,这似乎不再有任何作用.我什至无法验证SettingsSingleFileGenerator是否完全运行.此 GitHub问题表明这是采用新的.csproj格式的错误,但没有一个提供了替代方案.

Unfortunately, this no longer seems to do anything. I can't even verify that the SettingsSingleFileGenerator runs at all. This GitHub issue suggests that this is a bug with the new .csproj format, but no one has offered an alternative.

在.NET Core中读取.settings文件的正确方法是什么?

What is the proper way of reading .settings files in .NET core?

推荐答案

对于.NET Core 2.x,请使用Microsoft.Extensions.Configuration命名空间(请参见下面的注释),NuGet上有许多扩展名,您需要可以从环境变量到Azure Key Vault(更现实的是JSON文件,XML等)的源中进行读取.

For .NET Core 2.x, use the Microsoft.Extensions.Configuration namespace (see note below), and there are tons of extensions on NuGet you'll want to grab for reading from sources ranging from environment variables to Azure Key Vault (but more realistically, JSON files, XML, etc).

这是一个来自控制台程序的示例,该示例在Kestrel启动我们的Azure站点时以与使用设置相同的方式来检索设置:

Here's an example from a console program that retrieves settings the same way we use them when Kestrel starts up for our Azure sites:

public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)

    // This allows us to set a system environment variable to Development
    // when running a compiled Release build on a local workstation, so we don't
    // have to alter our real production appsettings file for compiled-local-test.
    //.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)

    .AddEnvironmentVariables()
    //.AddAzureKeyVault()
    .Build();

然后在需要设置的代码中,只需引用Configuration或注册IConfiguration进行依赖项注入或任何其他操作.

Then in your code that needs settings, you just reference Configuration or you register IConfiguration for dependency injection or whatever.

注意:IConfiguration是只读的,可能永远不会根据评论.因此,如果需要读写,您将需要其他选择.可能是System.Configuration sans 设计器.

Note: IConfiguration is read-only and will likely never get persistence per this comment. So if reading AND writing are required, you'll need a different option. Probably System.Configuration sans designer.

这篇关于如何在.NET Core中使用.settings文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 03:34