【问题标题】:ConfigurationManager.AppSettings.Get(key).ConvertTo error in asp.net coreASP.NET 核心中的 ConfigurationManager.AppSettings.Get(key).ConvertTo 错误
【发布时间】:2017-05-10 18:20:51
【问题描述】:

下面是我的代码。我尝试将下面的代码从 asp.net 转换为 asp.net 核心。但是在 asp.net 核心中最后一行 ConvertTo 显示错误,因为 Get(key) 没有 ConvertTo 的定义。不知道是什么问题。

我找不到任何解决方案,如何在 asp.net core 中编写以下代码?

    public static T Get<T>(string key)
    {
        if (!Exists(key))
        {
            throw new ArgumentException(String.Format("No such key in the AppSettings: '{0}'", key));
        }
        return ConfigurationManager.AppSettings.Get(key).ConvertTo<T>(new CultureInfo("en-US"));
    }

提前致谢。

【问题讨论】:

  • 请贴出转换失败的值。以及您要转换的类型。

标签: asp.net asp.net-core


【解决方案1】:

.net Core 中的配置现在大部分构建在 POCO 或 IOptions 之上。您不会获得单独的密钥,而是建立设置类。以前,您必须构建一个 CustomConfiguration 类,或者您将 AppSettings 前缀为“将它们分组”。不再!如果您采用使用 IOptions 的方法,它的工作原理类似于以下内容。

您的 appSettings.json 如下所示:

{
  "myConfiguration": {
    "myProperty": true 
  }
}

然后,您可以创建一个与您的配置相匹配的 POCO。像这样的东西:

public class MyConfiguration
{
    public bool MyProperty { get; set; }
}

然后在您的 startup.cs 中,您需要将配置加载到选项对象中。它最终看起来与以下内容非常相似。

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<MyConfiguration>(Configuration.GetSection("myConfiguration"));
    }
}

然后 DI 全部设置为注入 IOptions 对象。然后你可以像这样将它注入到控制器中:

public class ValuesController : Controller
{
    private readonly MyConfiguration _myConfiguration;

    public ValuesController(IOptions<MyConfiguration> myConfiguration)
    {
        _myConfiguration = myConfiguration.Value;
    }
}

还有其他方法可以做到这一点,不使用 IOptions 对象,您只需将 POCO 注入您的控制器。有些人(包括我)更喜欢这种方法。你可以在这里阅读更多:http://dotnetcoretutorials.com/2016/12/26/custom-configuration-sections-asp-net-core/

当然,官方文档的文档链接在这里:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration

【讨论】:

    【解决方案2】:

    我建议你先仔细阅读documentation。在 .NET Core 中,我们使用配置的方式发生了显着变化(使用不同的源、映射到 POCO 对象等)。

    在您的情况下,您可以简单地使用 ConfigurationBinder 的 GetValue&lt;T&gt; 扩展方法,而不是实现自己的值转换方法:

    IConfiguration.GetValue - 提取具有指定键的值 并将其转换为 T 类型。

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 1970-01-01
      • 2018-03-12
      • 2018-10-03
      • 2016-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-11
      相关资源
      最近更新 更多