欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.Net Core 读取配置文件 appsettings.json

程序员文章站 2024-02-01 19:49:28
.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();
    }
}