.Net核心发布后没有阅读appsetting

时间:2018-04-10 17:49:43

标签: c# asp.net-core .net-core

很快: 我的启动课程看起来像这样:

  public Startup(IHostingEnvironment env)
    {
        this.env = env;
        var builder = new ConfigurationBuilder()
          .SetBasePath(env.ContentRootPath)
          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
          .AddEnvironmentVariables();

        Configuration = builder.Build();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options =>
        {
            options.RespectBrowserAcceptHeader = true;
            options.FormatterMappings.SetMediaTypeMappingForFormat(
                "xml", MediaTypeHeaderValue.Parse("text/xml"));
            options.FormatterMappings.SetMediaTypeMappingForFormat(
                "json", MediaTypeHeaderValue.Parse("application/json"));
        })
        .AddXmlSerializerFormatters();

        var dbConfig = Configuration.GetSection(nameof(DbOptions)).Get<DbOptions>();
        services.AddDbContext<GamesDbContext>(opt => opt.UseSqlServer(dbConfig.ConnectionString));        
    }

和: 虽然我在本地主机上一切正常但是当我发布到网络时,应用程序会在每次请求时抛出状态:500内部服务器错误。我在想周围,事实证明,如果我更换

    var dbConfig = Configuration.GetSection(nameof(DbOptions)).Get<DbOptions>();
    services.AddDbContext<GamesDbContext>(opt => opt.UseSqlServer(dbConfig.ConnectionString));   

    services.AddDbContext<GamesDbContext>(opt => opt.UseSqlServer(@"connectionstring"));   

它在本地和外部都像魅力一样工作,所以我想问题在解析appsettings.js时存在问题,但它有什么问题呢? appsettings.Development.json基本上只是appsettings.json的复制粘贴

1 个答案:

答案 0 :(得分:0)

当我阅读代码时,我认为你的appSetting.Development.json结构看起来像那样

{
    "DbOptions": {
         "connectionstrings": ""
     }
}

但是,你的appSetting.json结构看起来像那样

{
     "connectionstrings": ""
}

我建议像那样使用

{
    "ConnectionStrings": {
        "DataContext": "Server=db;database=ProjectDb;uid=AppUser;pwd=AppPass;"
    },
    "Console": {
        "LogLevel": {
            "Default": "Warning"
         }
    }
}

你可以像这样轻松使用。

string sqlConnectionString = Configuration.GetConnectionString("DataContext");
services.AddDbContext<DataContext>(options => options.UseSql(sqlConnectionString));

在Microsoft.Extensions.Configuration类中有读取ConnectionStrings

的扩展名