【问题标题】:NullReferenceException thrown while reading config.json in MVC6在 MVC6 中读取 config.json 时抛出 NullReferenceException
【发布时间】:2015-10-13 16:06:36
【问题描述】:

我正在开发 MVC6 网络应用程序。我的 Startup.cs 有以下代码-

public class Startup
{
    public static Microsoft.Framework.ConfigurationModel.IConfiguration Configuration { get; set; }

    public Startup(IHostingEnvironment env)
    {
       //following line throws NullReferenceException
       Configuration = new Configuration().AddJsonFile("config.json").AddEnvironmentVariables();
    }
}

config.json-

{
    "Data": {
        "DefaultConnection": {
            "ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;"
         }
     }
}

有什么帮助吗?

更新:这个问题不仅仅与 NullReferenceException 有关。在 ASP.NET-5 MVC-6,config.json 是新增的。我正在使用代码作为 它可以在几个博客中找到。这里有几个链接-

【问题讨论】:

  • @RowlandShaw 这不是重复你提到的问题。这个问题在别处。所以,它不应该被关闭。
  • @RowlandShaw - 这里的问题不同。这个问题应该有答案了。
  • 你用的是什么版本,beta4?
  • 你至少可以弄清楚 new Configuration()AddJsonFile()AddEnvironmentVariables() 是否会抛出 NRE。

标签: asp.net-core asp.net-core-mvc


【解决方案1】:

如果您使用的是 RTM 版本的 Visual Studio,您必须使用 asp.net 的 beta5 版本。在此版本中,配置的命名空间已更改。

编辑:你必须添加这个包:Microsoft.Framework.Configuration.Json

此代码必须为您工作:

using Microsoft.Framework.Configuration;
using Microsoft.Framework.Runtime;

namespace Test
{
    public class Startup
    {
        public IConfiguration Configuration { get; set; }

        public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
        {
            var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
                .AddJsonFile("config.json")
                .AddEnvironmentVariables();

            Configuration = builder.Build();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 2020-11-17
    • 2016-03-21
    相关资源
    最近更新 更多