asp.net core mvc 控制器使用配置

一、在根目录 添加 mysettings.json 文件

mysettings.json 文件代码如下:

{
  "MySettings": {
    "Name": "独立配置文件",
    "Site": "lt"
  }
}

appsettings.json 文件代码如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "WebSettings": {
    "Name": "涛哥网站",
    "Site": "www.tg.com"
  }
}

二、core目录下添加相应的类

    public class WebSettings
    {
        public string Name { get; set; }
        public string Site { get; set; }
    }
    public class MySettings
    {
        public string Name { get; set; }
        public string Site { get; set; }
    }

 

三、Startup.cs 文件配置

1、将根路径中的JSON配置提供程序添加到生成器

public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
     var builder = new ConfigurationBuilder()
         .SetBasePath(env.ContentRootPath) //设置路径为网站根目录
         .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
         .AddJsonFile("mysettings.json", optional: true, reloadOnChange: true);

      Configuration = builder.Build();
}

2、添加配置类

public void ConfigureServices(IServiceCollection services)
{
    //添加配置类
    services.AddOptions();
    services.Configure(Configuration.GetSection("WebSettings"));
    services.Configure(Configuration.GetSection("MySettings"));
}

四、控制器中使用

Microsoft.Extensions.Options

public class HomeController : BaseController
{

   //通过一个字段来存储
   private WebSettings webOption;

   public HomeController(IOptions weboptions,IOptions myoptions)
   {
     webOption = weboptions.Value;
   }
}

你可能感兴趣的:(asp.net,core,mvc,asp.net,mvc,服务器)