ASP.NET CORE MVC 2.0 如何在Filter中使用依赖注入来读取AppSettings,及.NET Core控制台项目中读取AppSettings
问:
ASP.NET CORE MVC 如何在Filter中使用依赖注入来读取AppSettings
答:
Dependency injection is possible in filters as well.
Here is a simple way to get connection string
public class EBisUserAuthResourceFilter : Attribute, IResourceFilter
{
private readonly string connectionString; public EBisUserAuthResourceFilter(IConfiguration configuration)
{
this.connectionString = configuration
.GetSection("ConnectionStrings:DefaultConnection").Value;
}
public void OnResourceExecuted(ResourceExecutedContext context)
{
// use this.connectionString
} public void OnResourceExecuting(ResourceExecutingContext context)
{
// use this.connectionString
}
}
Now you can use this filter
[ServiceFilter(typeof(EBisUserAuthResourceFilter))]
public class HomeController : Controller
{ }
You also need to add this Filter to the service collection
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<EBisUserAuthResourceFilter>(); // your existing code to add other services
}
Another solution is to have a class representing the structure of the content of AppSettings.json file or a sub section and load that in your Startup classes' ConfigureServices method
services.Configure<SiteSettings>(Configuration);
and now you can inject IOptions<SiteSettings> in the constructor of your filter and use the needed property values. I prefer this as it is less magic strings in my code.
public class EBisUserAuthResourceFilter : Attribute, IResourceFilter
{
private readonly string connectionString; public EBisUserAuthResourceFilter(IOptions<SiteSettings> settings)
{
this.connectionString = settings.Value.connectionString ;
}
public void OnResourceExecuted(ResourceExecutedContext context)
{
// use this.connectionString
} public void OnResourceExecuting(ResourceExecutingContext context)
{
// use this.connectionString
}
}
补充:
当然还有个更简单的办法,就是在Filter里面直接通过.Net Core App的方式来读取AppSettings的值,这个方法是最灵活的:
appsettings.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"AppSettings": {
"CacheTimeSpan": 1200,
"MD5PrivateKey": "KOPX&VDtt!890912hjk",
"Auth_UserName": "Username",
"Auth_Token": "Token"
}
}
构造一个AppSettings类来反序列化appsettings.json文件中AppSettings节点下的内容:
public class AppSettings
{
public int CacheTimeSpan { get; set; }
public string MD5PrivateKey { get; set; }
public string Auth_UserName { get; set; }
public string Auth_Token { get; set; }
}
在Filter的构造函数中,构造AppSettings并读取其值:
public class AuthenticationFilterAttribute : Attribute, IAuthorizationFilter
{
public AuthenticationFilterAttribute()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); IConfigurationRoot configuration = builder.Build(); var appSettings=configuration.GetSection("AppSettings").Get<AppSettings>();
int cacheTimeSpanValue = appSettings.CacheTimeSpan;
} public void OnAuthorization(AuthorizationFilterContext context)
{ }
}
.NET Core控制台项目读取AppSettings
其实在.NET Core控制台项目中也可以创建和读取AppSettings
首先你需要在.NET Core控制台项目中确保引用了下面四个Nuget包:
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.Binder
- Microsoft.Extensions.Configuration.FileExtensions
- Microsoft.Extensions.Configuration.Json
接下来,我们就可以在.NET Core控制台项目中创建一个appsettings.json文件如下:
{
"AppSettings": {
"CacheTimeSpan": 1200,
"MD5PrivateKey": "YUIOOASSA!@!##",
"Auth_UserName": "Username",
"Auth_Token": "Token"
}
}
注意要将appsettings.json文件的属性做修改,将"Copy to Output Directory"选项设置为"Copy if newer",如下:


然后同样定义一个AppSettings类来反序列化appsettings.json文件中AppSettings节点下的内容:
public class AppSettings
{
public int CacheTimeSpan { get; set; }
public string MD5PrivateKey { get; set; }
public string Auth_UserName { get; set; }
public string Auth_Token { get; set; }
}
然后在.NET Core控制台项目的Main方法中,按照如下代码读取AppSettings的值即可:
using Microsoft.Extensions.Configuration;
using System;
using System.IO; namespace NetCoreEnvironmentVariable
{
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); IConfigurationRoot configuration = builder.Build(); var appSettings = configuration.GetSection("AppSettings").Get<AppSettings>();
int cacheTimeSpanValue = appSettings.CacheTimeSpan;
string authUserName = appSettings.Auth_UserName; Console.WriteLine($"CacheTimeSpan={cacheTimeSpanValue}");
Console.WriteLine($"Auth_UserName={authUserName}"); Console.WriteLine("Press any key to end...");
Console.ReadKey();
}
}
}
执行结果如下:

使用AddEnvironmentVariables方法配置读取操作系统的环境变量
我们还可以配置IConfigurationBuilder去加载操作系统环境变量的值,为此我们需要在.NET Core控制台项目中再引用一个Nuget包:
接下来我们在Windows操作系统中,添加两个环境变量:
AppSettings:CacheTimeSpan为5000
AppSettings:Password为abc123456
如下图所示:

之后,最好重启一下计算机,因为AddEnvironmentVariables方法使用类似于EnvironmentVariableTarget.Process参数的机制,来加载操作系统环境变量,所以需要重启计算机后才能够读取到操作系统环境变量的值。
然后我们将.NET Core控制台项目的Main方法改为如下:
using Microsoft.Extensions.Configuration;
using System;
using System.IO; namespace NetCoreEnvironmentVariable
{
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();//使用AddEnvironmentVariables方法,配置让IConfigurationBuilder加载操作系统中的环境变量,由于这里AddEnvironmentVariables方法在上面的AddJsonFile方法的后面,所以在"appsettings.json"文件中与操作系统环境变量同名的键值,会被操作系统环境变量的值所覆盖 IConfigurationRoot configuration = builder.Build(); var appSettings = configuration.GetSection("AppSettings").Get<AppSettings>();
int cacheTimeSpanValue = appSettings.CacheTimeSpan;//由于在操作系统环境变量中,我们定义了AppSettings:CacheTimeSpan为5000,所以"appsettings.json"文件中CacheTimeSpan为1200的值会被覆盖,所以这里实际上得到的是操作系统环境变量AppSettings:CacheTimeSpan的值5000
string authUserName = appSettings.Auth_UserName;//由于在操作系统环境变量中,没有定义AppSettings:Auth_UserName,所以这里得到的还是"appsettings.json"文件中Auth_UserName的值Username
string password = configuration["AppSettings:Password"];//获取操作系统环境变量AppSettings:Password的值abc123456 Console.WriteLine($"CacheTimeSpan={cacheTimeSpanValue}");
Console.WriteLine($"Auth_UserName={authUserName}");
Console.WriteLine($"Password={password}"); Console.WriteLine("Press any key to end...");
Console.ReadKey();
}
}
}
注意"appsettings.json"文件中的json类型层次结构,可以用冒号":"来进行表达,所以我们可以看到,上面代码中操作系统环境变量AppSettings:CacheTimeSpan,等同于"appsettings.json"文件中AppSettings属性下的CacheTimeSpan属性。
运行上面代码,执行结果如下:

可以看到,我们成功地读出了操作系统环境变量AppSettings:CacheTimeSpan和AppSettings:Password的值。
ASP.NET CORE MVC 2.0 如何在Filter中使用依赖注入来读取AppSettings,及.NET Core控制台项目中读取AppSettings的更多相关文章
- ASP.NET CORE MVC 2.0 项目中引用第三方DLL报错的解决办法 - InvalidOperationException: Cannot find compilation library location for package
目前在学习ASP.NET CORE MVC中,今天看到微软在ASP.NET CORE MVC 2.0中又恢复了允许开发人员引用第三方DLL程序集的功能,感到甚是高兴!于是我急忙写了个Demo想试试,我 ...
- ASP.NET Core 中文文档 第四章 MVC(3.8)视图中的依赖注入
原文:Dependency injection into views 作者:Steve Smith 翻译:姚阿勇(Dr.Yao) 校对:孟帅洋(书缘) ASP.NET Core 支持在视图中使用 依赖 ...
- ASP.NET Core Web 应用程序系列(一)- 使用ASP.NET Core内置的IoC容器DI进行批量依赖注入(MVC当中应用)
在正式进入主题之前我们来看下几个概念: 一.依赖倒置 依赖倒置是编程五大原则之一,即: 1.上层模块不应该依赖于下层模块,它们共同依赖于一个抽象. 2.抽象不能依赖于具体,具体依赖于抽象. 其中上层就 ...
- ADO.NET .net core2.0添加json文件并转化成类注入控制器使用 简单了解 iTextSharp实现HTML to PDF ASP.NET MVC 中 Autofac依赖注入DI 控制反转IOC 了解一下 C# AutoMapper 了解一下
ADO.NET 一.ADO.NET概要 ADO.NET是.NET框架中的重要组件,主要用于完成C#应用程序访问数据库 二.ADO.NET的组成 ①System.Data → DataTable, ...
- ASP.NET Core如何在ActionFilterAttribute里做依赖注入
在ASP.NET Core里,我们可以使用构造函数注入很方便地对Controller,ViewComponent等部件做依赖注入.但是如何给过滤器ActionFilterAttribute也用上构造函 ...
- ASP.NET Core 在 JSON 文件中配置依赖注入
前言 在上一篇文章中写了如何在MVC中配置全局路由前缀,今天给大家介绍一下如何在在 json 文件中配置依赖注入. 在以前的 ASP.NET 4+ (MVC,Web Api,Owin,SingalR等 ...
- ASP.NET Core中的依赖注入(2):依赖注入(DI)
IoC主要体现了这样一种设计思想:通过将一组通用流程的控制从应用转移到框架之中以实现对流程的复用,同时采用"好莱坞原则"是应用程序以被动的方式实现对流程的定制.我们可以采用若干设计 ...
- ASP.NET Core 中的依赖注入
目录 什么是依赖注入 ASP .NET Core 中使用依赖注入 注册 使用 释放 替换为其它的 Ioc 容器 参考 什么是依赖注入 软件设计原则中有一个依赖倒置原则(DIP),为了更好的解耦,讲究要 ...
- ASP.NET Core中的依赖注入(1):控制反转(IoC)
ASP.NET Core在启动以及后续针对每个请求的处理过程中的各个环节都需要相应的组件提供相应的服务,为了方便对这些组件进行定制,ASP.NET通过定义接口的方式对它们进行了"标准化&qu ...
随机推荐
- 使用RabbitMQ实现延迟任务----实用场景
1. 使用RabbitMQ实现延迟任务
- child_process
child_process const { spawn } = require('child_process'); const ls = spawn('ls', ['-lh', '/usr']); l ...
- 关于纯css写三角形在firefox下的锯齿问题
相信很多人都用过利用border来实现小三角箭头,百度一下,这类的文章多如牛毛,这里我还是啰嗦点把常用的方法陈列出来: .triangle_border_up{ width:; height:; bo ...
- hadoop 3.0.0 alpha3 安装、配置
1. 官网下载 wget http://mirror.bit.edu.cn/apache/hadoop/common /hadoop-3.0.0-alpha3/hadoop-3.0.0-alpha3 ...
- 02_dubbo的SPI
[dubbo为什么不采用JDK自带的SPI] 1.JDK自带的SPI(ServiceLoader)会一次性实例化扩展点所有实现,基本只能通过遍历全部获取,也就是接口的实现类全部加载并实例化一遍,如果我 ...
- Android MediaPlayer播放音乐并实现进度条
提前工作,往sd卡里放音乐文件 1.布局文件main.xml <?xml version="1.0" encoding="utf-8"?> < ...
- androidUI异步消息
private Handler handler = new Handler(){ public void handleMessage(android.os.Message msg) { switch ...
- C++ 类对象的初始化顺序 ZZ
C++构造函数调用顺序 1. 创建派生类的对象,基类的构造函数优先被调用(也优先于派生类里的成员类): 2. 如果类里面有成员类,成员类的构造函数优先被调用:(也优先于该类本身的构造函数 ...
- mongodb数据库备份恢复-windows系统
备份语法: mongodump命令脚本语法如下: >mongodump -h dbhost -d dbname -o dbdirectory -h: MongDB所在服务器地址,例如:127.0 ...
- 小程序——微信小程序初学踩过的坑
微信小程序初学踩过的坑 一.前言 最近因为某些需要和个人兴趣打算开发一下微信小程序,经过在官方网站上的基本了解,我大体知道了微信小程序开发的大致过程,其实最本质的就是MVVM,借用了很多模式上 ...