![](Screenshots/Focal-Length-Comparison-Rockt-Launch-1536x1022.jpg)
# Table of Contents
<!-- TOC -->
* [Introduction](#introduction)
* [How Does This Work?](#how-does-this-work)
* [How The Settings Are Merged At Runtime](#how-the-settings-are-merged-at-runtime)
* [Configuring for Development & Production Environments](#configuring-for-development--production-environments)
* [The Settings Configuration Setup](#the-settings-configuration-setup)
* [File: `appsettings.json`](#file--appsettingsjson)
* [File: `appsettings.Development.json`](#file--appsettingsdevelopmentjson)
* [File: `appsettings.Production.json`](#file--appsettingsproductionjson)
* [Implementation](#implementation)
* [Settings](#settings)
* [Implementation - Sample Console Application](#implementation---sample-console-application)
* [Conclusion](#conclusion)
* [References](#references)
<!-- TOC -->
# Introduction
`Asp.Net` applications support `Development` & `Production` settings out of the box with `appsettings.json` via environment-driven multiple files - `appsettings.json`, `appsettings.Development.json`, and `appsettings.Production.json`.
`appsettings.json` is just one of many places where application settings can be set. You can read more about this here: [Configuration providers in .NET | Microsoft Learn](https://learn.microsoft.com/en-us/dotnet/core/extensions/configuration-providers)
This article will focus on adding support for `appsettings.json` to other applications types, specifically `Console`, `Winforms`, and `WPF` types.
Whilst not critical, to get a better understanding, we will look into the Dot Net source code and see how Microsoft's configuration works. What we will cover is documented in the link above. Then we will do a quick test in a `Console` application to better understand how and why.
# How does this work?
We need to look at how the framework wires up the `appsettings.json`. To do this, we need to explore the implementation in the framework code, specifically the `Hostbuilder.ConfigureDefaults` in `HostingHostBuilderExtensions` class:
```csharp
internal static void ApplyDefaultHostConfiguration(IConfigurationBuilder hostConfigBuilder, string[]? args)
{
// If we're running anywhere other than C:\Windows\system32, we default to using the CWD for the ContentRoot.
// However, since many things like Windows services and MSIX installers have C:\Windows\system32 as there CWD which is not likely
// to really be the home for things like appsettings.json, we skip changing the ContentRoot in that case. The non-"default" initial
// value for ContentRoot is AppContext.BaseDirectory (e.g. the executable path) which probably makes more sense than the system32.
// In my testing, both Environment.CurrentDirectory and Environment.GetFolderPath(Environment.SpecialFolder.System) return the path without
// any trailing directory separator characters. I'm not even sure the casing can ever be different from these APIs, but I think it makes sense to
// ignore case for Windows path comparisons given the file system is usually (always?) going to be case insensitive for the system path.
string cwd = Environment.CurrentDirectory;
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || !string.Equals(cwd, Environment.GetFolderPath(Environment.SpecialFolder.System), StringComparison.OrdinalIgnoreCase))
{
hostConfigBuilder.AddInMemoryCollection(new[]
{
new KeyValuePair<string, string?>(HostDefaults.ContentRootKey, cwd),
});
}
hostConfigBuilder.AddEnvironmentVariables(prefix: "DOTNET_");
if (args is { Length: > 0 })
{
hostConfigBuilder.AddCommandLine(args);
}
}
```
Here we can see that an Environment variable with the prefix `DOTNET_` is used.
You can read more about this here: [.NET Generic Host | Microsoft Learn](https://learn.microsoft.com/en-us/dotnet/core/extensions/generic-host)
To get the suffix, we look at the comments in `IHostEnvironment`for the `EnvironmentName` property:
```csharp
/// <summary>
/// Provides information about the hosting environment an application is running in.
/// </summary>
public interface IHostEnvironment
{
/// <summary>
/// Gets or sets the name of the environment. The host automatically sets this property to the value of the
/// "environment" key as specified in configuration.
/// </summary>
string EnvironmentName { get; set; }
/// <summary>
/// Gets or sets the name of the application. This property is automatically set by the host to the assembly containing
/// the application entry point.
/// </summary>
string ApplicationName { get; set; }
/// <summary>
/// Gets or sets the absolute path to the directory that contains the application content files.
/// </summary>
string ContentRootPath { get; set; }
/// <summary>
/// Gets or sets an <see cref="IFileProvider"/> pointing at <see cref="ContentRootPath"/>.
/// </summary>
IFileProvider ContentRootFileProvider { get; set; }
}
```
So the suffix is `Environment`. So the complete environment variable name is `DOTNET_ENVIRONMENT`. Unlike `Asp.Net` and it's `ASPNETCORE_ENVIRONMENT` variable, the `DOTNET_ENVIRONMENT` is not set by default.
When there is no environment variable set, the `EnviromentName` defaults to `Production` and, if it exists, `appsettings.Production.json` for both `Debug` and `Release` modes even if the `appsettings.Development.json` exists. `appsettings.Development.json` will be ignored.
# How The Settings Are Merged At Runtime
We need to look at another extension method in `HostingHostBuilderExtensions` class:
```csharp
internal static void ApplyDefaultAppConfiguration(HostBuilderContext hostingContext, IConfigurationBuilder appConfigBuilder, string[]? args)
{
IHostEnvironment env = hostingContext.HostingEnvironment;
bool reloadOnChange = GetReloadConfigOnChangeValue(hostingContext);
appConfigBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: reloadOnChange)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: reloadOnChange);
if (env.IsDevelopment() && env.ApplicationName is { Length: > 0 })
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly is not null)
{
appConfigBuilder.AddUserSecrets(appAssembly, optional: true, reloadOnChange: reloadOnChange);
}
}
appConfigBuilder.AddEnvironmentVariables();
if (args is { Length: > 0 })
{
appConfigBuilder.AddCommandLine(args);
}
```
What we are interested in is this:
```csharp
appConfigBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: reloadOnChange)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: reloadOnChange);
```
Here we can see that the `appsettings.json` is loaded first, then the `$"appsettings.{env.EnvironmentName}.json"` where the `EnvironmentName` is dependent on the `DOTNET_ENVIRONMENT` environment variable. As we know from above, unless we manually choose one, `EnvironmentName` will default to `Production`.
Any settings in the `appsettings.json` will be overridden by the `appsettings.Production.json` values if set.
# Configuring for Development & Production Environments
To set the `DOTNET_ENVIRONMENT` variable, open the application 'Properties' by right-clicking on the application name in the `Solution Explorer`, navigate to `Debug` > `General` section and click on the 'open debug launch profiles UI'. This will open the `Launch Profile` window.
![Application Properties > Debug section](Screenshots/Properties.png)
Or we can access the Launch Profiles window from the toolbar:
![](Screenshots/Toolbar Run Settings 1.png)
What we are interested in is the `Environment variables`. You can
没有合适的资源?快使用搜索试试~ 我知道了~
AppSettings-v1.01.zip
共25个文件
json:10个
png:4个
cs:2个
需积分: 5 0 下载量 8 浏览量
2024-02-19
21:30:02
上传
评论
收藏 167KB ZIP 举报
温馨提示
在本文中,你将了解如何为non-ASP.NET Core应用程序(控制台、Winforms和WPF)启用开发和生产AppSettings支持——包括C#和VB示例
资源推荐
资源详情
资源评论
收起资源包目录
AppSettings_v1.01.zip (25个子文件)
AppSettings
AppSettings
appsettings.Development.json 88B
Properties
launchSettings.json 548B
MySectionOptions.cs 154B
Program.cs 1017B
AppSettings.csproj 2KB
appsettings.json 87B
appsettings.Staging.json 84B
appsettings.Production.json 87B
AppSettings.csproj.user 392B
AppSettings.sln 2KB
readme.md 16KB
Screenshots
Toolbar Run Settings 1.png 10KB
Focal-Length-Comparison-Rockt-Launch-1536x1022.jpg 51KB
LaunchProfiles.png 37KB
Properties.png 49KB
Toolbar Run Settings 2.png 10KB
AppSettingsVB
My Project
Application.myapp 435B
launchSettings.json 548B
appsettings.Development.json 88B
MySectionOptions.vb 116B
Program.vb 1KB
appsettings.json 87B
appsettings.Staging.json 84B
appsettings.Production.json 87B
AppSettingsVB.vbproj 1KB
共 25 条
- 1
资源评论
寒冰屋
- 粉丝: 997
- 资源: 573
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功