ASP.NET Core MVC创建并关联JSON配置文件
1.目录下创建 appsettings.json文件
内容:
{
"ConnectionStrings": {
"DefaultConnection": "Databases = InMemory;",
"Myname": "Lihuahua;"
}
}
2.创建Settings文件夹下,新增类
类具体内容:(属性的名字和appsettings.json文件中键值对的键相对应)
namespace TestMvc.Settings
{
public class ConnectionStringOptions
{
public string DefaultConnection { get; set; }
public string Myname { get; set; }
}
}
3.在Startup方法中注册服务
//Startup中添加
//构造方法
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
ConfigureServices方法中关联服务
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();//使用该方法后才可以使用app.UseMvc()方法
services.AddSingleton<Ifactory, Factory>();
//关联起来
services.Configure<ConnectionStringOptions>(_configuration.GetSection("ConnectionStrings"));
}
4.引用
csHtml中引用
@using Microsoft.Extensions.Options;
@inject IOptions<TestMvc.Settings.ConnectionStringOptions> ioption;
<div class="jumbotron">
<h1 class="display-4"> @ioption.Value.Myname</h1>
</div>
后台引用
public class HomeController:Controller
{
//构造方法中初始化值
private IOptions<ConnectionStringOptions> option;
public HomeController(IOptions<ConnectionStringOptions> options)
{
this.option = options;
}
}
PS:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context,builder)=> {
builder.//这里选择添加配置文件的格式
})
.UseStartup<Startup>();