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. 读取不标准的JSON数据

    正常的JSON数据 [      {"key":"UI","value":"UII"},      {"key ...

  2. Nodejs学习笔记(十七)--- 浮点运算decimal.js

    目录 前言 JavaScript加减乘除运算 decimal.js加减乘除运算 前言 开发过程中免不了有浮点运算,JavaScript浮点运算的精度问题会带来一些困扰 JavaScript 只有一种数 ...

  3. The authenticity of host 'github.com (192.30.253.113)' can't be established.

    在初始化git之后(git init),同时在github建立好仓库之后,本地也新增了ssh kye(ssh-keygen -t rsa -C 'mail address'),同时也在本地新增了远程仓 ...

  4. 写出优雅又地道的pythonic代码(转自网络)

    本文是Raymond Hettinger在2013年美国PyCon演讲的笔记(视频, 幻灯片). 示例代码和引用的语录都来自Raymond的演讲.这是我按我的理解整理出来的,希望你们理解起来跟我一样顺 ...

  5. (三)—Linux文件传输与mysql数据库安装

    文件传输工具使用    为了速成,关于linux系统的学习都先放一放,用到哪个知识点就查哪个,这里想在linux下装一些服务练练手,最先想到的就是装个mysql数据库试试. 因为我用的是虚拟机下的li ...

  6. python 中Dict 转 Json

    近期在公司须要写个小工具.运用到的python,然后须要将Dict转成Json. 之前遇到转换Json失败,然后以为复杂的Entity结构.不能用Json的库Json.dump().进行转换. 自己些 ...

  7. JAVA入门[20]-Spring Data JPA简单示例

    Spring 对 JPA 的支持已经非常强大,开发者只需关心核心业务逻辑的实现代码,无需过多关注 EntityManager 的创建.事务处理等 JPA 相关的处理.Spring Data JPA更是 ...

  8. 基于Office 365的随需应变业务应用平台

    作者:陈希章 发表于 2017年9月7日 这是我去年10月底在微软技术大会(Microsoft Ignite 2016) 上面的演讲主题,承蒙大家抬爱,也沾了前一场明星讲师的光,我记得会场几乎是满座. ...

  9. Java连接MySQL数据库增删改查通用方法

    版权声明:本文为博主原创文章,未经博主允许不得转载. Java连接MySQL数据库增删改查通用方法 运行环境:eclipse+MySQL 以前我们Java连接MySQL数据库都是一个数据库写一个类,类 ...

  10. 字符设备 Vs. 块设备 Character Device Vs. Block Device

    字符设备是指驱动发送/接受单个字符(例如字节)的设备. 块设备是指驱动发送/接受整块数据(例如512个字节为一个块)的设备. 常见的字符设备:串口,并口,声卡. 常见的块设备:硬盘(最小读取单位为扇区 ...