【问题标题】:Empty Asp.net Core Project do not Have appsettings.json file空的 Asp.net Core 项目没有 appsettings.json 文件
【发布时间】:2019-05-17 15:35:44
【问题描述】:

我创建了一个 Asp.net Core 项目,但不包含 appsettin.json 文件

我像这样编辑 Startup.cs 文件:

public class Startup
{

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseDeveloperExceptionPage();
        app.UseStatusCodePages();
        app.UseStaticFiles();
        app.UseMvc();

    }
}

【问题讨论】:

  • 你有什么问题?如果你问为什么没有appsettings.json,那是因为你选择了空项目选项。如果你想要一个appsettings.json 文件,只需创建一个。

标签: c# asp.net-core


【解决方案1】:

如果您查看Program.cs,您将看到以下代码:

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

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>();

特别感兴趣的是WebHost.CreateDefaultBuilder,它的定义如下:

public static IWebHostBuilder CreateDefaultBuilder(string[] args)
{
    var builder = new WebHostBuilder();

    if (string.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey)))
    {
        builder.UseContentRoot(Directory.GetCurrentDirectory());
    }
    if (args != null)
    {
        builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());
    }

    builder.ConfigureAppConfiguration((hostingContext, config) =>
    {
        var env = hostingContext.HostingEnvironment;

        config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
              .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

        if (env.IsDevelopment())
        {
            var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
            if (appAssembly != null)
            {
                config.AddUserSecrets(appAssembly, optional: true);
            }
        }

        config.AddEnvironmentVariables();

        if (args != null)
        {
            config.AddCommandLine(args);
        }
    })
    .ConfigureLogging((hostingContext, logging) =>
    {
        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
        logging.AddConsole();
        logging.AddDebug();
        logging.AddEventSourceLogger();
    }).
    UseDefaultServiceProvider((context, options) =>
    {
        options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
    });

    ConfigureWebDefaults(builder);

    return builder;
}

这是很多代码,但请注意它,因为了解默认情况下发生的情况很重要。

对于您的主要问题,使用 appsettings.json 添加 JSON 配置提供程序。换句话说,您不必直接在Startup 中添加此提供程序,因为它已经由CreateDefaultBuilder 添加。其他配置提供程序(如环境变量、命令行参数、用户机密等)以及基本日志记录也是如此。所有这些都是开箱即用的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 2018-03-20
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    相关资源
    最近更新 更多