NullReferenceException thrown while reading config.json in MVC6

亡梦爱人 提交于 2019-12-08 11:33:04

问题


I'm working on MVC6 webapp. My Startup.cs has the following code-

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

Any help?

UPDATE: This question is not all about NullReferenceException. In ASP.NET-5 MVC-6, config.json is a new addition. I am using the code as it is found in several blogs. Here are few links-

  • http://bitoftech.net/2014/11/18/getting-started-asp-net-5-mvc-6-web-api-entity-framework-7/
  • https://github.com/aspnet/MusicStore/blob/master/src/MusicStore/Startup.cs
  • http://forums.asp.net/t/1999143.aspx?How+to+configure+connection+string+in+MVC+6+in+ASP+NET+vNext
  • http://blog.developers.ba/read-config-file-in-asp-net-vnext/

回答1:


If you are using the RTM version of Visual Studio you must be working with beta5 revision of asp.net. In this version namespaces for configuration has been changed.

EDIT: You must add this package: Microsoft.Framework.Configuration.Json

This code must work for you:

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


来源:https://stackoverflow.com/questions/31585880/nullreferenceexception-thrown-while-reading-config-json-in-mvc6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!