2016-12-26 110 views
0

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

我无法找到任何解决方案如何在asp.net核心下面编写代码?

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")); 
    } 

在此先感谢。

+1

请张贴未能转换的值。你想要转换成什么类型​​。 –

回答

0

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

在你的情况,你可以简单地使用ConfigurationBinder的GetValue<T>扩展方法,而不是实现了价值的转换自己的方法:

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

0

.net Core中的配置现在基本上建立在POCO或IOption之上。你没有得到个人密钥,而是建立了设置类。以前,您必须构建一个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