【问题标题】:ASP.NetCore 2.2 reading in appsettings.jsonASP.Net Core 2.2 读取 appsettings.json
【发布时间】:2019-09-05 15:31:16
【问题描述】:

ASP.NetCore 2.2、VisualStudio 2019

我正在尝试弄清楚如何将 web.configfile 转换为 appsettings.json,但我错过了一些东西。

我有一个 startup.cs 文件,看起来像(为简洁而编辑):

using System;
using MyCoolApp.Models.Commodities;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace MyCoolApp {
    public class Startup {
        public Startup(IHostingEnvironment env) {
            var builder = new ConfigurationBuilder()
                .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                .AddJsonFile("appsettings.json", true, true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
                .AddEnvironmentVariables();

            Configuration = builder.Build();
        }

        private IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services) {
            services.AddDistributedMemoryCache();

            services.Configure<IISServerOptions>(
                options => { 
                    options.AutomaticAuthentication = false; 
                }
            );

            services.AddMvc().SetCompatibilityVersion(
                CompatibilityVersion.Version_2_2
            );

            var foo = Configuration.GetConnectionString("CommoditiesContext");
            services.AddDbContext<CommoditiesContext>(
                options => options.UseSqlServer(
                    Configuration.GetConnectionString("CommoditiesContext")
                )
            );

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
            ...
        }
    }
}

注意var foo = Configuration.GetConnectionString(...) 行。

我有一个web.config 文件,看起来像(经过大量编辑):

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="CommoditiesContext" connectionString="Server=mydb.company.com;Initial Catalog=Things;Integrated Security=True;providerName=System.Data.SqlClient;" />
  </connectionStrings>
</configuration>

我已经把它变成了“顶级”appsettings.json 文件:

{
    "Logging": {
        "LogLevel": {
            "Default": "Warning"
        }
    },
    "AllowedHosts": "*",
    "connectionStrings": {
        "CommoditiesContext": "Server=mydb.company.com;Initial Catalog=Things;Integrated Security=True;providerName=System.Data.SqlClient;"
    }
}

我有一个appsettings.Development.json 文件,看起来像:

{
    "Logging": {
        "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information"
        }
    },
    "location": {
        "path": ".",
        "inheritInChildApplications": "false",
        "system.webServer": {
            "handlers": [],
            "aspNetCore": {
                "processPath": "%LAUNCHER_PATH%",
                "arguments": "%LAUNCHER_ARGS%",
                "stdoutLogEnabled": "true",
                "stdoutLogFile": ".\\logs\\stdout",
                "hostingModel": "InProcess",
                "environmentVariables": [
                    {
                        "name": "ASPNETCORE_HTTPS_PORT",
                        "value": "44375"
                    },
                    {
                        "name": "ASPNETCORE_ENVIRONMENT",
                        "value": "Development"
                    },
                    {
                        "name": "COMPLUS_ForceENC",
                        "value": "1"
                    }
                ],
                "handlerSettings": [
                    {
                        "name": "debugFile",
                        "value": "aspnetcore-debug.log"
                    },
                    {
                        "name": "debugLevel",
                        "value": "FILE,TRACE"
                    }
                ]
            },
            "modules": [],
            "isapiFilters": []
        }
    }
}

我也有一个“生产”,但暂时让我们限制噪音。

我现在的问题是,当我在本地调试它时,我可以在startup.csservices.AddDbContext 行上设置一个bp,然后查看foo 的值。它是null。我要么错误地构建了appsettings.json 文件,要么错误地读取了配置信息,但我不知道是哪个。

我错过了什么?

编辑

program.cs

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace CalendarReservations {
    public class Program {
        public static void Main(string[] args) {
            CreateWebHostBuilder(args).Build().Run();
        }

        private static IWebHostBuilder CreateWebHostBuilder(string[] args) {
            return WebHost.CreateDefaultBuilder(args)
                .UseIIS()
                .UseStartup<Startup>();
        }
    }
}

【问题讨论】:

  • FWIW,你的appsettings.Development.json 完全没用。 web.config 和 appsettings.json 之间没有一对一的关联。 location 指令之类的东西不适用,system.webServer 之类的部分也不适用。 JSON 只是数据,配置提供程序会将所有这些转换为键值对的扁平化字典,键值类似于 location:system.webServer:aspNetCore:processPath。就是这样。这些实际上不会有任何影响。它们只是静态设置。
  • 呃,.NetCore 不是我的朋友。我发现没有 1:1 的相关性,但如果有提供的转换工具或更好的文档或其他东西会很好。
  • 问题在于这些都是 IIS 设置,而 ASP.NET Core 不需要 IIS,因此它们是单独配置的。 appsettings.json et al 用于应用程序配置;不适用于 IIS 配置。

标签: c# asp.net-core


【解决方案1】:

问题是您在启动构造函数中为配置设置了错误的基本路径。 AppDomain.CurrentDomain.BaseDirectory 会给你错误的位置,因此不会加载任何配置文件。相反,请考虑改用System.IO.Directory.GetCurrentDirectory()

【讨论】:

    【解决方案2】:

    从你的代码中取出这个 (startup.cs)

    var builder = new ConfigurationBuilder()
                    .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                    .AddJsonFile("appsettings.json", true, true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
                    .AddEnvironmentVariables();
    
                Configuration = builder.Build();
    

    编辑:正如柯克在 cmets 中指出的那样

    你需要这样替换它

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    

    为什么?因为如果你的 Program.cs 类中有这个

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
    

    那你就不用自己设置了

    基于 ASP.NET Core dotnet new 的默认配置 Web 应用 模板在构建主机时调用 CreateDefaultBuilder。 CreateDefaultBuilder 为应用程序提供默认配置 以下顺序:

    以下内容适用于使用 Web 主机的应用程序。有关详细信息 使用通用主机时的默认配置,见最新 本主题的版本。

    主机配置来自:环境变量前缀 与 ASPNETCORE_(例如,ASPNETCORE_ENVIRONMENT)一起使用 环境变量配置提供程序。前缀 (ASPNETCORE_) 在加载配置键值对时被剥离。 使用命令行配置提供程序的命令行参数。 应用程序配置来自:appsettings.json 使用文件 配置提供者。 appsettings.{Environment}.json 使用文件 配置提供者。应用程序运行时的 Secret Manager 使用入口程序集的开发环境。环境 使用环境变量配置提供程序的变量。 使用命令行配置提供程序的命令行参数。

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2

    【讨论】:

    • 如果我删除您建议的部分,那么我在同一条船上:appsettings 未被阅读。如果我保留该部分并添加@DavidG 的建议,我确实看到了我正在寻找的连接字符串。
    • 你不能只是删除提到的代码;您还需要将IConfiguration 注入您的Startup 并将其分配给您的Configuration 属性。
    猜你喜欢
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多