ASP.NET Core读取appsettings.json配置文件信息

Posted zhouxiaoyun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ASP.NET Core读取appsettings.json配置文件信息相关的知识,希望对你有一定的参考价值。

1、在配置文件appsettings.json里新增AppSettings节点

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AppSettings": {
    "HttpUrl": "http://www.ehongcn.com",
    "Copyright": "山南远宏科技有限公司"
  },
  "AllowedHosts": "*"
}

2、新建实体类AppSettings,通常建在公共类库Common里

    public class AppSettings
    {
        public string HttpUrl { get; set; }
        public string Copyright { get; set; }
    }

3、在Startup类里的ConfigureServices配置

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

4、控制器或者业务类里使用

        private readonly AppSettings _appSettings;

        public HomeController(IOptions<AppSettings> appSettings)
        {
            _appSettings = appSettings.Value;
        }

        public IActionResult Index()
        {
            ViewData["Url"] = _appSettings.HttpUrl;
            return View();
        }

5、页面上使用

@using Microsoft.Extensions.Options;
@using Demo.Common
@inject IOptions<AppSettings> Settings
@{
    ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>

<p>版权所属有 @Settings.Value.Copyright.</p>

 

以上是关于ASP.NET Core读取appsettings.json配置文件信息的主要内容,如果未能解决你的问题,请参考以下文章

asp.net core 读取appsettings.json

ASP.NET Core读取appsettings.json配置文件信息

ASP.NET CORE读取appsettings.json的配置

在 ASP.NET Core 的 ConfigureServices 阶段实际读取 AppSettings

.net core读取appsettings.json配置

在 asp net core 控制台应用程序中读取 appsettings