【无标题】

简介

  在我们之前的Asp.net mvc 开发中,一提到配置文件,我们不由的想到 web.config 和 app.config,在 core 中,我们看到了很多的变化,新的配置系统显得更加轻量级,具有更好的扩展性,并且支持多样化的数据源。

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

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

appsettings.json

   在 第二章icon-default.png?t=N2N8http://www.cnblogs.com/yuangang/p/5695033.html 中,我们在讲到EF上线文时,在 Startup.cs 添加 services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection"))); 已经使用到了 appsettings.json 

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

{
    "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

 public class ApplicationConfiguration
      {
          #region 属性成员
  
          /// <summary>
          /// 文件上传路径
          /// </summary>
         public string FileUpPath { get; set; }
          /// <summary>
         /// 是否启用单用户登录
         /// </summary>
         public bool IsSingleLogin { get; set; }
         /// <summary>
         /// 允许上传的文件格式
         /// </summary>
         public string AttachExtension { get; set; }
         /// <summary>
         /// 图片上传最大值KB
         /// </summary>
         public int AttachImagesize { get; set; }
         #endregion
     }

  在 Startup.cs 的 ConfigureServices 添加

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

  

添加一个领域层 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;

我们来测试一下:  

  测试结果:  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值