Asp.Net Core 进阶(一) —— 读取appsettings.json

  我们以前在Asp.Net MVC中使用 System.Configuration.ConfigurationManager 来读取web.config文件。但是Asp.Net Core MVC已经没有web.config文件了,它的配置信息一般写在appsettings.json当中,那么我们怎么读取该文件呢?

  在Asp.Net Core MVC中使用 Microsoft.Extensions.Options.ConfigurationExtensions 包来读取appsettings.json。具体的操作如下:

  使用NuGet添加  Microsoft.Extensions.Options.ConfigurationExtensions  包到我们的项目当中,然后在appsettings.json中添加我们自己的一些配置信息

{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "ConnectionStrings": { "OpenAuthDBContext": "Data Source=localhost;Initial Catalog=dbname;User=sa;Password=123" }, "AppSetting": { "SSOPassport": "http://localhost:52789", "Version": "1.0", //如果为demo,则屏蔽Post请求 "DbType": "SqlServer", //数据库类型:SqlServer/MySql "MessageUrl": "http://localhot:23124", //短信平台接口 "MessageType": "CAD71325-0097-4052-9183-56F04EED0B31" //短信类型ID }}

  然后我们新建一个文件AppSetting

 /// <summary> /// 配置项 /// </summary> public class AppSetting { public AppSetting() { SSOPassport = "http://localhost:52789"; Version = ""; DbType = Define.DBTYPE_SQLSERVER; } /// <summary> /// SSO地址 /// </summary> public string SSOPassport { get; set; } /// <summary> /// 版本信息 /// 如果为demo,则屏蔽Post请求 /// </summary> public string Version { get; set; } /// <summary> /// 数据库类型 SqlServer、MySql /// </summary> public string DbType { get; set; } /// <summary> /// 短信平台接口Url /// </summary> public string MessageUrl { get; set; } /// <summary> /// 短信类型 /// </summary> public string MessageType { get; set; } }

  接着在Startup.cs文件的ConfigureServices方法中添加

services.AddOptions();//映射配置文件services.Configure<AppSetting>(Configuration.GetSection("AppSetting"));

  最后就可以在我们的Controller中使用了,通过IOption<AppSetting>来读取。

private readonly IOptions<AppSetting> _setting; public LoginController(IAuth authUtil,IOptions<AppSetting> setting){ _authUtil = authUtil; _setting = setting;}public string GetCaptcha(string phone){ string messageUrl = _setting.Value.MessageUrl; string messageType = _setting.Value.MessageType; if (_authUtil.GetCaptcha(phone, messageUrl, messageType)) { return JsonHelper.Instance.Serialize(new { Code = 200, Message = "" }); } return JsonHelper.Instance.Serialize(new { Code = 500, Message = "验证码获取失败,请稍后重试!" });}

  需要注意的是,通过IOption的方式不能在Startup.cs中读取appsettings.json文件,在Startup.cs中读取appsettings.json文件需要使用Microsoft.Extensions.Configuration的IConfiguration。

var dbType = ((ConfigurationSection) Configuration.GetSection("AppSetting:DbType")).Value;

 或者使用

var v = Configuration["ASPNETCORE_ENVIRONMENT"];var d = Configuration["AppSetting:MessageUrl"];

 针对格式为下面的json,我么可以通过索引来获取

{ "Message": { "Message1": { "Name": "" }, "Message2": { "Name": "" } }}
_configuration["Message:0:Name"]

 

相关文章