今天在把之前一个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的,是一种装逼模式,需要项目引用Nuget包(在ASP.NET Core 2.0项目中这个Nuget包默认就是被引用了的):

Microsoft.Extensions.Options.ConfigurationExtensions

然后在ASP.NET Core项目Startup类的构造函数中,配置Configuration对象:

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

    http://www.tuicool.com/articles/rQruMzV 今天在把之前一个ASP.NET MVC5的Demo项目重写成ASP.NET Core,发现原先我们一直用的Configu ...

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

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

  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. 《ASP.NET MVC企业实战》(三)MVC开发前奏

    ​ 在上一篇“<ASP.NET MVC企业级实战>(二)MVC开发前奏”中跟随作者大概了解了一些C#3.0和3.5中的新特性.本篇继续以这样的方式来学习C#中的一些特性.   一.C#3. ...

  2. Android Studio列表用法之一:ListView图文列表显示(实例)

    前言: ListView这个列表控件在Android中是最常用的控件之一,几乎在所有的应用程序中都会使用到它. 目前正在做的一个记账本APP中就用到了它,主要是用它来呈现收支明细,是一个图文列表的呈现 ...

  3. Android Studio 在项目中引用第三方jar包

    在Android Studio项目中引用第三方jar包的方法: 步骤: 1.在build.gradle文件中添加如下代码: 备注:要添加在Android作用域下 sourceSets { main { ...

  4. Android事件总线(三)otto用法全解析

    前言 otto 是 Square公司发布的一个发布-订阅模式框架,它基于Google Guava 项目中的event bus模块开发,针对Android平台做了优化和加强.虽然Square已经停止了对 ...

  5. Python:BeautifulSoup移除某些不需要的属性

    很久之前,我看到一个问题,大概是: 他爬了一段html,他获取下了所需的部分(img标签部分),但是不想保留img标签的某些属性, 比如 <img width="147" h ...

  6. WebStorm连接Github教程

    上学期刚开学的时候看过一次git相关的内容,很久没用过,忘了,两个月前又看了一次还精心做了笔记,也没有具体使用,又忘了,所以,避免又双叒叕忘了,我决定正式把git用起来.刚开始是通过Git Bash来 ...

  7. 洗礼灵魂,修炼python(25)--自定义函数(6)—从匿名函数进阶话题讲解中解析“函数式编程”

    匿名函数进阶 前一章已经说了匿名函数,匿名函数还可以和其他内置函数结合使用 1.map map():映射器,映射 list(map(lambda x:x*2,range(10))) #把range产生 ...

  8. WebAPi使用Autofac实现依赖注入

    WebAPi依赖注入  使用记录 笔记 1.NuGet包安装 2.控制器加入构造函数 3.Global.asax  ----Application_Start 应用程序启动时 using Autofa ...

  9. entity framework异常 The specified cast from a materialized 'System.Int32' type to the 'System.String' type is not valid

    ROW_NUMBER() OVER (ORDER BY (select Null)) AS Id entity framework 查询中有这句会有异常

  10. Android 电池系列

    android 电池(一):锂电池基本原理篇 android 电池(二):android关机充电流程.充电画面显示 android 电池(三):android电池系统 android电池(四):电池 ...