之前在Startup.cs是这样读取config.json的:
public Startup(IApplicationEnvironment appEnv) { Configuration = new Configuration(appEnv.ApplicationBasePath) .AddJsonFile("config.json"); }
升级至ASP.NET 5 RC1后,运行dnx kestrel出现下面的错误:
cannot convert from 'string' to 'Microsoft.Framework.ConfigurationModel.IConfigurationSource' at Microsoft.Dnx.Compilation.CSharp.RoslynProjectReference.Load(AssemblyName assemblyName, IAssemblyLoadContext loadContext) at Microsoft.Dnx.Compilation.CompilationEngine.LoadProject(Project project, FrameworkName targetFramework, String aspect, IAssemblyLoadContext loadContext, AssemblyName assemblyName) at Microsoft.Dnx.Runtime.Loader.ProjectAssemblyLoader.Load(AssemblyName assemblyName, IAssemblyLoadContext loadContext) at Microsoft.Dnx.Runtime.Loader.ProjectAssemblyLoader.Load(AssemblyName assemblyName) at Microsoft.Dnx.Host.LoaderContainer.Load(AssemblyName assemblyName) at Microsoft.Dnx.Host.DefaultLoadContext.LoadAssembly(AssemblyName assemblyName) at Microsoft.Dnx.Runtime.Loader.AssemblyLoaderCache.GetOrAdd(AssemblyName name, Func`2 factory) at Microsoft.Dnx.Runtime.Loader.LoadContext.Load(AssemblyName assemblyName)
换用下面这行代码试试。
public IConfiguration Configuration { get; set; } public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { var builder = new ConfigurationBuilder() .SetBasePath(appEnv.ApplicationBasePath) .AddJsonFile("config.json"); Configuration = builder.Build(); }
在新的ASP.net5中,读取配置文件的过程是:
1、在Setup类中,通过ConfigurationBuilder(配置相关的唯一入口)创建ConfigurationProvider(此例中被封装在了扩展方法“AddJsonFile中”)
2、通过“Build()方法对外提供IConfiguration接口”,该接口使业务逻辑不依赖于具体的ConfigurationProvider。
正解。还需要将命名空间由 using Microsoft.Framework.ConfigurationModel 改为 using Microsoft.Extensions.Configuration;