ASP.NET MVC 6连接Sting config.json

时间:2016-01-02 09:00:05

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

我遇到的问题是当我运行程序时出现“System.NullReferenceException”异常。不确定是什么问题。此问题也不允许我使用dnx启动数据迁移。

enter image description here

enter image description here

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using School.Models;

namespace School.Context
{
    public class SchoolDbContext : DbContext
    {
       public DbSet<Course> Courses {get; set;}
    }
} 

scoolDbContext.cs

namespace School
{
public class Startup
{
    public static Microsoft.Extensions.Configuration.IConfiguration Configuration { get; set; }

    public Startup (IHostingEnvironment env)
    {
        //setup configuration sources
        Configuration = new ConfigurationBuilder()
       .AddJsonFile("config.json")
       .AddEnvironmentVariables()
       .Build();

    }
    // 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)
    {
        //add services to container
        services.AddEntityFramework().AddSqlServer().AddDbContext<SchoolDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
        services.AddMvc();

        //resolve dependency injections
        services.AddScoped<IRegistrationRepo, RegistrationRepo>();
        services.AddScoped<SchoolDbContext, SchoolDbContext>();           
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app)
    {
        app.UseIISPlatformHandler();
        app.UseMvc();
        app.UseWelcomePage();

    }

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

Statup.cs

{{1}}

enter image description here

1 个答案:

答案 0 :(得分:1)

你应该修改代码

public Startup (IHostingEnvironment env)
{
    //setup configuration sources
    Configuration = new Configuration()
        .AddJsonFile("config.json")
        .AddEnvironmentVariables();
}

public Startup (IHostingEnvironment env)
{
    //setup configuration sources
    Configuration = new ConfigurationBuilder()
        .AddJsonFile("config.json")
        .AddEnvironmentVariables()
        .Build();
}

public Startup (IHostingEnvironment env)
{
    //setup configuration sources
    Configuration = new ConfigurationBuilder()
        .AddJsonFile("config.json")
        .AddJsonFile($"config.{env.EnvironmentName}.json", true)
        .AddEnvironmentVariables()
        .Build();
}