.Net Core 读取 appsettings.json

Posted 大豆男生

tags:

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

1. 首先些一个类

public class MySettings
{
    public string P1 { get; set; }
    public string P2 { get; set; }
}

2. 在 appsettings.json 中添加配置项

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "MySettings": {
    "P1": "p1_value",
    "P2": "p2_value"
  }
}

3. 修改 Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<MySettings>(Configuration.GetSection("MySettings"));
    services.AddMvc();
}

4.  修改 HomeController.cs

public class HomeController : Controller
{
    private MySettings mySettings { get; set; }

    public HomeController(IOptions<MySettings> mySettings)
    {
        this.mySettings = mySettings.Value;
    }

    public IActionResult Index()
    {
        string p1 = mySettings.P1; 
        return View();
    }
}

 

  

  

 

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

ASP.NET Core读取AppSettings

asp.net core 读取appsettings.json

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

.net core读取appsettings.config中文乱码问题

.Net Core 读取 appsettings.json

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