在MVC6中读取config.json时引发NullReferenceException [英] NullReferenceException thrown while reading config.json in MVC6
问题描述
我正在开发MVC6 Web应用程序.我的Startup.cs具有以下代码-
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-
config.json-
{
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;"
}
}
}
有帮助吗?
更新:这个问题不仅仅与NullReferenceException有关.在ASP.NET-5 MVC-6,config.json是新增功能.我正在使用代码作为在几个博客中都可以找到它.这里有几个链接-
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-
- https://github.com/aspnet/MusicStore/blob/master/src/MusicStore/Startup.cs
- http://forums.asp.net/t/1999143.aspx?如何+配置+连接+字符串+ in + MVC + 6 + in + ASP + NET + vNext >
- http://blog.developers.ba/read-config-file-in-asp-net-vnext/
推荐答案
如果使用的是Visual Studio的RTM版本,则必须使用asp.net的beta5修订版.在此版本中,用于配置的名称空间已更改.
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.
,您必须添加以下程序包: Microsoft.Framework.Configuration.Json
You must add this package: 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();
}
}
}
这篇关于在MVC6中读取config.json时引发NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!