今天在把之前一个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. 一次关于()=>({})的使用

    今天遇到了一个问题,值得一记 首先在我看项目代码时发现了一个问题 有一个JS的export如下 大家可以注意一下config 这里为什么要如此写法呢? 首先这里用的时ES6的箭头函数 ()=>{ ...

  2. CSS的引入方式及CSS选择器

    一 CSS介绍 现在的互联网前端分三层: a.HTML:超文本标记语言.从语义的角度描述页面结构. b.CSS:层叠样式表.从审美的角度负责页面样式. c.JS:JavaScript .从交互的角度描 ...

  3. 转: Laravel 自定义公共函数的引入

    来源:Laravel 自定义公共函数的引入 背景习惯了 使用 ThinkPHP 框架,有一个公共方法类在代码编写上会快捷很多,所以有必要在此进行配置一番.测试框架:Laravel 5.5步骤指导1. ...

  4. 图片缩放PhoneView

    第一步:导包 implementation 'com.github.chrisbanes:PhotoView:2.0.0' 第二步:加bmob仓库地址 在build.gradle(project)中的 ...

  5. idea 自动换行

    如下:

  6. Java:构造代码块,静态代码块

    本文内容: 局部代码块 构造代码块 静态代码块 补充 首发日期:2018-03-28 局部代码块: 局部代码块用于限制变量的生命周期,如果希望某些变量在某一过程之后直接失效而不希望被后面继续操作时,可 ...

  7. 安装VisualSVN Server 报"Service 'VisualSVN Server' failed to start. Please check VisualSVN Server log in Event Viewer for more details"错误.原因是启动"VisualSVN Server"失败

    安装VisualSVN Server 报"Service 'VisualSVN Server' failed to start. Please check VisualSVN Server ...

  8. SQLSERVER 死锁

    select request_session_id spid, OBJECT_NAME(resource_associated_entity_id) tableName from sys.dm_tra ...

  9. Xcode调试LLDB

    一.简介 关于Xcode调试,相信大家很多会用断点调试,今天无意间在苹果开发的群里看到了po,瞬间心中有个疑问:po是什么?下面我就百度搜索了一下,介绍一点皮毛. 首先是LLDB,它的全名是lower ...

  10. ABAP 7.50 新特性之另一个CORRESPONDING

    在ABAP中,存在着一条法则:同样的名称代表的不一定是同样的东西(具体可看最近的相关讨论). 但是如你们所知的,存在着一个很好的例外: 所有涉及到使用CORRESPONDING为结构赋值的关键字的语法 ...