前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ASP.NET Core appsettings.json文件(9)《从零开始学ASP.NET CORE MVC》:

ASP.NET Core appsettings.json文件(9)《从零开始学ASP.NET CORE MVC》:

作者头像
角落的白板报
发布2019-05-05 14:49:58
1.3K0
发布2019-05-05 14:49:58
举报
文章被收录于专栏:角落的白板报角落的白板报

本文出自《从零开始学ASP.NET CORE MVC》 推荐文章:ASP.NET Core launchsettings.json文件

ASP.NET Core appsettings.json文件

在本视频中,我们将讨论ASP.NET Core 项目中appsettings.json文件的重要性。

在以前的ASP.NET版本中,我们将应用程序配置设置(例如数据库连接字符串)存储在web.config文件中。 在 Asp.Net Core 中, 应用程序配置设置可以来自以下不同的配置源。

  • 文件(appsettings.json, appsettings.{Environment}.json) Environment环境不同,托管在对应环境。
  • User secrets (用户机密)
  • Environment variables (环境变量)
  • Command-line arguments (命令行参数)

appsettings.json f文件: 我们的项目是通过Asp.net Core 预制的"空"模板创建的,所以我们的项目中已经有一个appsettings.json 的文件了。 我们可以对文件进行如下修改,补充一个MyKey的键值对:

代码语言:javascript
复制
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "MyKey": " appsettings.json中Mykey的值",
}

访问配置信息

若要访问 "Startup " 类中的配置信息, 请注入框架提供的 IConfiguration服务。Startup类位于 startup. cs 文件中。

代码语言:javascript
复制
public class Startup
{
    private IConfiguration _configuration;

    // 注意,我们在这里使用了依赖注入
    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync(_configuration["MyKey"]);
        });
    }
}

依赖注入

在以前版本的ASP.NET中,依赖注入是可选的,要配置它,我们必须使用像Ninject,autofac、castle windsor等第三方框架。

在 asp. net Core 中, 依赖注入是不可或缺的一部分。依赖注入能使我们能够创建低耦合、可扩展且易于测试的系统。

我们将在即将推出的视频中详细讨论依赖注入,尽情期待。

ASP.NET Core IConfiguration 服务

  • IConfiguration 服务是为了从asp.net Core 中的所有各种配置源读取配置信息而设计的。
  • 如果在多个配置源中具有相同密钥名称的配置设置,简单来说就是重名了,则后面的配置源将覆盖先前的配置源 。

几个地方的演示,分别是如何替换的。 launchsetting

  • 静态类WebHostCreateDefaultBuilder()方法在应用程序启动时会自动去调用,按特定顺序读取配置源。
  • 要查看配置源的读取顺序,请查看以下链接上的ConfigureAppConfiguration()方法 https://github.com/aspnet/MetaPackages/blob/release/2.2/src/Microsoft.AspNetCore/WebHost.cs

检查文件后,您将看到,以下是读取各种配置源的默认顺序

  1. appsettings.json,
  2. appsettings.{Environment}.json
  3. 用户机密
  4. 环境变量 5.命令行参数

如果您想要改变他们的调用顺序,甚至往里面添加属于自己的自定义配置信息,我们将在后面的课程中讨论如何自定义配置源。

小结

所以翻源代码也没有那么可怕嘛

代码语言:javascript
复制
/// <summary>
        /// Initializes a new instance of the <see cref="WebHostBuilder"/> class with pre-configured defaults using typed Startup.
        /// </summary>
        /// <remarks>
        ///   The following defaults are applied to the returned <see cref="WebHostBuilder"/>:
        ///     use Kestrel as the web server and configure it using the application's configuration providers,
        ///     set the <see cref="IHostingEnvironment.ContentRootPath"/> to the result of <see cref="Directory.GetCurrentDirectory()"/>,
        ///     load <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostingEnvironment.EnvironmentName"/>].json',
        ///     load <see cref="IConfiguration"/> from User Secrets when <see cref="IHostingEnvironment.EnvironmentName"/> is 'Development' using the entry assembly,
        ///     load <see cref="IConfiguration"/> from environment variables,
        ///     load <see cref="IConfiguration"/> from supplied command line args,
        ///     configure the <see cref="ILoggerFactory"/> to log to the console and debug output,
        ///     enable IIS integration.
        /// </remarks>
        /// <typeparam name ="TStartup">The type containing the startup methods for the application.</typeparam>
        /// <param name="args">The command line args.</param>
        /// <returns>The initialized <see cref="IWebHostBuilder"/>.</returns>
        public static IWebHostBuilder CreateDefaultBuilder<TStartup>(string[] args) where TStartup : class =>
            CreateDefaultBuilder(args).UseStartup<TStartup>();
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-04-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 角落的白板报 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档