http://www.tuicool.com/articles/rQruMzV

今天在把之前一个ASP.NET MVC5的Demo项目重写成ASP.NET Core,发现原先我们一直用的ConfigurationManager.AppSettings[]读取Web.config中的AppSettings节点的方法没用了。.NET Core有许多新的做法,我挑了一个最合适我自己项目的来分享一下我的实现方式。

首先,原来的代码:

web.config

...
<appSettings>
...
<add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=YOURACCOUNT;AccountKey=YOURKEY" />
<add key="AzureStorageAccountContainer" value="YOURCONTAINER" />
...
</appSettings>
...

Controller:

private static CloudBlobContainer GetBlobContainer()
{
string connectionString = WebConfigurationManager.AppSettings["StorageConnectionString"];
...
blobClient.GetContainerReference(WebConfigurationManager.AppSettings["AzureStorageAccountContainer"]);
return container;
}

这也是ASP.NET以来我们一直用来读web.config的方式。如果你想了解更装逼的方式,可以参考我的这篇文章: 《如何高逼格读取Web.config中的AppSettings》 ,文章里解决的问题主要是一个强类型的配置项,然而ASP.NET Core可以更方便的实现这个逼格。

首先,ASP.NET Core的设置文件用的是appsettings.json,而不是web.config,对于ASP.NET Core来说,web.config只是在部署到Windows服务器的时候给IIS用的配置,和ASP.NET Core一点卵关系都没有。

这个appsettings.json定义的格式如下:

{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

我把自己的配置项加进去就可以这样写:

{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"AppSettings": {
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=YOURACCOUNTNAME;AccountKey=YOURKEY",
"AzureStorageAccountContainer": "YOURCONTAINERNAME"
}
}

接下来,新建一个C#的Class,对应你的配置项:

public class AppSettings
{
public string StorageConnectionString { get; set; } public string AzureStorageAccountContainer { get; set; }
}

然后打开Startup.cs,把ConfigureServices这个方法改成这样(假设你是用ASP.NET Core的Web Application模板创建的网站)

public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddOptions();
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddMvc();
}

这个方法是做IOC的,是一种装逼模式,我们要装进去的逼用的是Snippet

Microsoft.Extensions.Options.ConfigurationExtensions

所以,得确保你的project.json里面有这项:

"dependencies": {
...
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
...
},

Configuration这个对象,在ASP.NET Core Web Applictaion的默认模板里已经自动撸好了,代码如下:

public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
} public IConfigurationRoot Configuration { get; }

然后Configuration.GetSection("AppSettings")这个里面的"AppSettings"对应的就是刚才json文件里配置的"AppSettings"节点。

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

这行代码的意思就是,一旦我们的应用里要用AppSettings这个类型,就用Configuration.GetSection("AppSettings")的结果来替代,.NET Core会自动帮我们做类型转换和mapping,把我在 《如何高逼格读取Web.config中的AppSettings》 里面装的逼全装掉了。

最后,你在Controller里用的时候就得按照IOC的一贯装逼方法,把构造函数装成这样:

private AppSettings AppSettings { get; set; }

public HomeController(IOptions<AppSettings> settings)
{
AppSettings = settings.Value;
}

然后就能愉快的使用强类型的config了:

private CloudBlobContainer GetBlobContainer()
{
string connectionString = AppSettings.StorageConnectionString;
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container =
blobClient.GetContainerReference(AppSettings.AzureStorageAccountContainer);
return container;
}

ASP.NET Core读取AppSettings的更多相关文章

  1. Asp .Net Core 读取appsettings.json配置文件

         Asp .Net Core 如何读取appsettings.json配置文件?最近也有学习到如何读取配置文件的,主要是通过 IConfiguration,以及在Program中初始化完成的. ...

  2. ASP.NET Core读取AppSettings (转载)

    今天在把之前一个ASP.NET MVC5的Demo项目重写成ASP.NET Core,发现原先我们一直用的ConfigurationManager.AppSettings[]读取Web.config中 ...

  3. asp.net core读取appsettings.json,如何读取多环境开发配置

    摘要 在读取appsettings.json文件中配置的时候,觉得最简单的方式就是使用asp.net core注入的方式进行读取了. 步骤 首先根据配置项的结构定义一个配置类,比如叫AppSettin ...

  4. asp.net core 读取appsettings.json配置项

    1.新建一个asp.net core 项目 2.打开appsettings.json,加入配置项 { "Logging": { "IncludeScopes": ...

  5. ASP.NET CORE读取appsettings.json的配置

    如何在appsettings.json配置应用程序设置,微软给出的方法:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/config ...

  6. asp.net core 读取Appsettings.json 配置文件

    Appsettingsjson 配置定义实体在StartUp时读取配置信息修改你的Controller通过构造函数进入配置信息总结Appsettings.json 配置很明显这个配置文件就是一个jso ...

  7. ASP.NET Core读取appsettings.json配置文件信息

    1.在配置文件appsettings.json里新增AppSettings节点 { "Logging": { "LogLevel": { "Defau ...

  8. Asp.Net Core 之 appsettings.json

    原文:Asp.Net Core 之 appsettings.json appsettings.json是什么? 相信大家在.Net Framework的项目都会用的web.config,app.con ...

  9. .net core 读取appsettings.json乱码

    .net core 读取配置文件乱码:vs2019读取appsettings.json乱码问题; .net core 读取appsettings.json乱码问题;用notepad++或者其他编辑器打 ...

随机推荐

  1. 使用superMap实现点标注和区域着色

    1.定义html文件,引入superMap的js和theme文件: <script src='${_ctxPath }/statics/js/superMap/SuperMap.Include. ...

  2. 有关nginx的配置文件 之server

    下面是vhost中的其中一个xxxx.conf文件 . [Shell] 纯文本查看 复制代码 ? 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 ...

  3. Redis各个数据类型的使用场景

    Redis支持五种数据类型:string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合). Redis列表命令 参考:http://www.r ...

  4. MongoDB入门学习(一):MongoDB的安装和管理

    以前用MySQL数据库,整天都是写大堆大堆的SQL语句,要记住这些SQL关键字都要花好几天时间,写的蛋都爆了,当接触到MongoDB的时候,发现不用写SQL,瞬间觉得高大上,瞬间产生了学习使用它的冲动 ...

  5. python项目依赖管理分享迁移后重建开发环境(一)virtualenv 和 pip

    作者:Panda Fang 出处:http://www.cnblogs.com/lonkiss/p/rebuild-development-environment-with-virtualenv-an ...

  6. java学习总结篇二--3 种简单排序

    本篇文章,先从数据结构开始,一边总结,一边反思,寻求最优解. 本文简单温习下最基础的三类算法:选择,冒泡,插入.先定义一个交换数组作为备用: /** * 交换数组元素 * @param arr * @ ...

  7. Java内存模型—JMM

     有时候编译器.处理器的优化会导致runtime与我们设想的不一样,为此Java对编译器和处理器做了一些限制,JAVA内存模型(JMM)将这些抽象出来,这样编写代码时就无需考虑那么多底层细节,并保证& ...

  8. 关于Oracle处理DDL和DML语句的事务管理

    SQL主要程序设计语言 数据定义语言DDL(Data Definition Language) 如 create.alter.drop, 数据操作语言DML(Data Munipulation Lan ...

  9. Android之不须要自己定义View(ViewfindView.java)最简单的二维码扫描

    不废话,先爆照 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/d ...

  10. Android-Volley网络通信框架(ImageRequest,ImageLoader,NetWorkImageView)

    1.回想 上篇已经学习了,RequestQueue  , StringRequest ,JsonObjectRequest 的使用 2.重点 (1)Volley请求图片的三种方式 (2)ImageRe ...