问题
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