首页 > 解决方案 > 未映射强类型配置设置

问题描述

我正在尝试在我的 ASP.NET Core 2.1 应用程序中设置强类型配置设置。

在我的 startup.cs 文件中,我有以下代码:

services.Configure<AzureStorageConfig>(Configuration.GetSection("AzureStorageConfig"));

我的设置类 AzureStorageConfig 如下所示:

public class AzureStorageConfig
{
    public string StorageConnectionString { get; internal set; }
}

我的 appSetting.json:

{
 "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
        "Default": "Debug",
        "System": "Information",
        "Microsoft": "Information"
    }
 },
 "AzureStorageConfig": {
    "StorageConnectionString": "UseDevelopmentStorage=true"
 }
}

当我运行代码时,我的 AzureStorageConfig.StorageConnectionString 始终为空。

如果我在 startup.cs 文件中设置断点,我可以看到设置在那里:

在此处输入图像描述

但是在注入 AzureStorageConfig 时,它为空。

public class RestaurantService : IRestaurantService
{
    private AzureStorageConfig m_Config;

    public RestaurantService(IOptions<AzureStorageConfig> config)
    {
        m_Config = config.Value;
    }
}

在此处输入图像描述

我想我有这里描述的一切:https ://weblog.west-wind.com/posts/2016/May/23/Strongly-Typed-Configuration-Settings-in-ASPNET-Core

标签: c#asp.net-core

解决方案


您的StorageConnectionString属性有一个internal设置器,但这需要public在尝试从您的Configuration实例绑定时让绑定器使用它:

public class AzureStorageConfig
{
    public string StorageConnectionString { get; set; }
}

推荐阅读