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. video字幕无法显示,video视频在google中无法控制快进

    video字幕(track)无法显示: 直接用关闭同源策略的浏览器打开你的HTML文件可以请求到字幕文件并显示字幕: 从hbuilder中打开html文件,在从里面打开google浏览器去浏览HTML ...

  2. 多线程 - pthread、NSThread

    1. pthread pthread 简单介绍下,pthread是一套通用的多线程的API,可以Unix / Linux / Windows 等徐彤跨平台使用,使用C语言编写,需要程序员自己管理线程的 ...

  3. Scala中的override

    Scala中的override override是覆盖的意思,在很多语言中都有,在scala中,override是非常常见的,在类继承方面,它和java不一样,不是可写可不写的了,而是必须写的.如果不 ...

  4. Swift 线程安全数组

    欢迎大家前往腾讯云社区,获取更多腾讯海量技术实践干货哦~ 作者:BigNerdCoding 有并发的地方就存在线程安全问题,尤其是对于 Swift 这种还没有内置并发支持的语言来说线程安全问题更为突出 ...

  5. Python函数篇(5)-装饰器及实例讲解

    1.装饰器的概念   装饰器本质上就是一个函数,主要是为其他的函数添加附加的功能,装饰器的原则有以下两个: 装饰器不能修改被修饰函数的源代码 装饰器不能修改被修改函数的调用方式   装饰器可以简单的理 ...

  6. 如何编写一个稳定的网络程序(TCP)

    本节我们看一下怎样才能编写一个基于TCP稳定的客户端或者服务器程序,主要以试验抓包的方式观察数据包的变化,对网络中出现的多种情况进行分析,分析网络程序中常用的技术及它们出现的原因,在之后的编程中能早一 ...

  7. 关于[LeetCode]Factorial Trailing Zeroes O(logn)解法的理解

    题目描述: Given an integer n, return the number of trailing zeroes in n!. 题目大意: 给定一个整数n,返回n!(n的阶乘)结果中后缀0 ...

  8. 大白话Vue源码系列(03):生成AST

    阅读目录 AST 节点定义 标签的正则匹配 解析用到的工具方法 解析开始标签 解析结束标签 解析文本 解析整块 HTML 模板 未提及的细节 本篇探讨 Vue 根据 html 模板片段构建出 AST ...

  9. 10_Eclipse中演示Git冲突的解决

     1 在user1中的readme.txt文件里先改动,而且commitand push 选中user1,右击team->Commit-à watermark/2/text/aHR0cDov ...

  10. Vue深度学习(6)- 组件

    使用组件 在Vue中,可以用 Vue.extend() 创建一个组件构造器: var MyComponent = Vue.extend({ template:'..........' //选项 }) ...