【无私分享:ASP.NET CORE 项目实战(第六章)】读取配置文件(一) appsettings.json

 

目录索引 

 

【无私分享:ASP.NET CORE 项目实战】目录索引html

 

简介

 

  在咱们以前的Asp.net mvc 开发中,一提到配置文件,咱们不禁的想到 web.configapp.config,在 core 中,咱们看到了不少的变化,新的配置系统显得更加轻量级,具备更好的扩展性,而且支持多样化的数据源。web

  博客园对于这个的讲解不少,好比:Artche ,可是,没有点基础看老A的博客仍是有些吃力的,对于老A介绍的配置,我也是看的一头雾水,在后面的文章中,我会用像咱们这些菜鸟容易接受的方式,从新解释一下。json

  今天,咱们以 appsettings.json 为例,读取一些简单的系统配置。
mvc

 

 

appsettings.json

 

    第二章 中,咱们在讲到EF上线文时,在 Startup.cs 添加 services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection"))); 已经使用到了 appsettings.json app

  咱们添加一些简单的系统配置,来演示一下读取 appsettings.json:post

  

  {
    "ApplicationInsights": {
      "InstrumentationKey": ""
    },
    "ConnectionStrings": {
      "SqlServerConnection": "Server=.;Database=db_wkmvc;User ID=sa_wkmvc;Password=123456;"
    },
    "Logging": {
      "IncludeScopes": false,
      "LogLevel": {
        "Default": "Debug",
        "System": "Information",
        "Microsoft": "Information"
      }
    },
    "ApplicationConfiguration": {
      //文件上传路径
      "FileUpPath": "/upload/",
      //是否启用单用户登陆
      "IsSingleLogin": "True",
      //容许上传的文件格式
      "AttachExtension": "gif,jpg,jpeg,png,bmp,rar,zip,doc,docx,xls,xlsx,ppt,pptx,txt,flv,apk,mp4,mpg,ts,mpeg,mp3,bak,pdf",
      //图片上传最大值KB
      "AttachImagesize": 12400
    }
  }学习

 

咱们添加一个配置类 ApplicationConfiguration测试

 

 1 public class ApplicationConfiguration
 2     {
 3         #region 属性成员
 4 
 5         /// <summary>
 6         /// 文件上传路径
 7         /// </summary>
 8         public string FileUpPath { get; set; }
 9         /// <summary>
10         /// 是否启用单用户登陆
11         /// </summary>
12         public bool IsSingleLogin { get; set; }
13         /// <summary>
14         /// 容许上传的文件格式
15         /// </summary>
16         public string AttachExtension { get; set; }
17         /// <summary>
18         /// 图片上传最大值KB
19         /// </summary>
20         public int AttachImagesize { get; set; }
21         #endregion
22     }

 

 

  Startup.cs 的 ConfigureServices 添加url

  services.Configure<ApplicationConfiguration>(Configuration.GetSection("ApplicationConfiguration"));spa

  

 

添加一个领域层 AppConfigurtaionServices

 

  public class AppConfigurtaionServices
  {
    private readonly IOptions<ApplicationConfiguration> _appConfiguration;
    public AppConfigurtaionServices(IOptions<ApplicationConfiguration> appConfiguration)
    {
      _appConfiguration = appConfiguration;
    }

    public ApplicationConfiguration AppConfigurations
    {
      get
        {
          return _appConfiguration.Value;
        }
    }
  }  

   添加引用 using Microsoft.Extensions.Options;

  

  咱们来测试一下:

  

 

 

  测试结果:

  

 

 

 

 

 

但愿跟你们一块儿学习Asp.net Core 

刚开始接触,水平有限,不少东西都是本身的理解和翻阅网上大神的资料,若是有不对的地方和不理解的地方,但愿你们指正!

虽然Asp.net Core 如今很火热,可是网上的不少资料都是前篇一概的复制,因此有不少问题我也暂时没有解决,但愿你们能共同帮助一下!

 

原创文章 转载请尊重劳动成果 http://yuangang.cnblogs.com

相关文章
相关标签/搜索