.net core appsetting/获取配置文件

修改appsetting

最近用Identity4因此须要作一个配置项项目json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "Indentity": {"Center": "",//这部分就是要取的 "ApiCenter": ""
  }
}

 

在startup中获取

首先咱们要从 Indentity中 获取center当中的数据app

这部分比较简单只要在startup 中的ConfigureServices 获取 Indentity下的Centeride

this.Configuration["Indentity:Center"]

就这么一句话就能够获取到了ui

将内容注入到管道中

1.建立一个modelthis

    public class IndentitySettingModel
    {
        public string Center { get; set; }
        public string ApiCenter { get; set; }
    }

2.在startup中注入到管道当中spa

 

services.Configure<Utility.HelperModel.IndentitySettingModel>(this.Configuration.GetSection("Indentity"));

兄弟。这样就注入到管道当中了。接下来咱们就能够去controller中获取 了code

在controller中获取

        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <returns></returns>
        public string GetAccessToken(IOptions<IndentitySettingModel> settings)
        {
           return settings.Center;
        }

恩很 就是这样 就能够获取的到了。blog

 

最详细的config引用

刚才有几个朋友和我说 。我干的很漂亮纯属糊弄人的文章。get

好的。 我从新写一下吧。string

我把全部须要引用DLL 给你们贴图吧。太多了。

算了,仍是打出来吧。

Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Abstractions
Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.Options
Microsoft.Extensions.Options.ConfigurationExtensions

把这些 nuget引用

编写Help类

    public class ConfigurationUtil
    {

        public static readonly IConfiguration Configuration;

        static ConfigurationUtil()
        {
            Configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", true)
                .Build();
        }

        public static T GetSection<T>(string key) where T : class, new()
        {
            var obj = new ServiceCollection()
                .AddOptions()
                .Configure<T>(Configuration.GetSection(key))
                .BuildServiceProvider()
                .GetService<IOptions<T>>()
                .Value;
            return obj;
        }

        public static string GetSection(string key)
        {
            return Configuration.GetValue<string>(key);
        }
    }

调用方法

ConfigurationUtil.GetSection("MongoDb:ConnectionString")

 

骂人部分

每天让我写。每天没人点赞!

后续

建立了一个QQ群但愿有志之士能够加一下

点击连接加入群聊【.Net Core研究团】:https://jq.qq.com/?_wv=1027&k=5298dNv

相关文章
相关标签/搜索