Configuration.AddJsonFile(" config.json")NullReferenceException

时间:2016-02-11 09:39:45

标签: asp.net-core-mvc

当我想添加addJsonFile时,我会使用NullReferenceException。我很清楚lynda(http://www.lynda.com/ASP-NET-tutorials/Dynamically-control-behavior-custom-configuration/368051/431234-4.html)说的是什么。 (screenShot

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNet.Diagnostics;
using Microsoft.Framework.Internal;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.ConfigurationModel.Json;

namespace PortalDemo
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            var config = new Configuration();

            config.AddEnvironmentVariables();
            config.AddJsonFile("config.json");//Here

            if (config.Get("debug") == "True")
            {
                app.UseRuntimeInfoPage();
                app.UseDeveloperExceptionPage();

            }
            app.UseExceptionHandler("/home/errorPage");

            app.UseMvc(routes=> 
            routes.MapRoute("Default","{controller=Home}/{action=Index}/{id?}"));

            app.UseStaticFiles();  
        }

        // Entry point for the application.
        public static void Main(string[] args) => WebApplication.Run<Startup>(args);
    }
}

1 个答案:

答案 0 :(得分:0)

请尝试以下代码。

public class Startup
{
    public Startup(IApplicationEnvironment appEnv)
    {
        IConfigurationBuilder builder = new ConfigurationBuilder()
            .SetBasePath(appEnv.ApplicationBasePath)
            .AddJsonFile("config.json", false);
        Configuration = builder.Build();           
    }

    public IConfiguration Configuration { get; set; }
}
相关问题