net Core 2.0读取appsettings.json
程序员文章站
2023-12-28 14:20:34
...
今天有朋友咨询这个问题,相信一些朋友也会遇到于是在这里写出来给大家提供一些参考
第一种方法:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
var b = Configuration["SQLConnection:Connecting"].ToString();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
第二种方法:
首先在appsettings.json里面定义自己的连接字符串或是其它想要读取的信息我这里定义的信息如下:
{
"Logging": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Warning"
}
},
"SQLConnection": {
"Connecting": "server=localhost;User Id=root;password=123456;Database=mytest"
}
}
然后创建一个Model,SQLConnection.cs,内容如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1
{
public class SQLConnection
{
/// <summary>
/// 连接字符串
/// </summary>
public string Connecting { get; set; }
}
}
再在Startup中ConfigureServices中添加如下代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<SQLConnection>(this.Configuration.GetSection("SQLConnection"));
}
再创建一个显示的页面Index.cshtml
public class IndexModel : PageModel
{
public SQLConnection LinkSQL;
//重写构造函数,包含注入的配置信息
public IndexModel(IOptions<StartInfo> setting, IOptions<SQLConnection> conection)
{
LinkSQL = conection.Value;
}
public void OnGet()
{
ViewData["SQL"] = LinkSQL.Connecting;}
推荐阅读
-
net Core 2.0读取appsettings.json
-
.NET Core读取配置文件appsettings.json
-
Asp .Net Core 读取appsettings.json配置文件
-
Asp .Net Core 读取appsettings.json配置文件
-
asp.net core 读取Appsettings.json 配置文件
-
asp.net core 2.0 webapi集成signalr(实例讲解)
-
Asp.Net Core 2.0 项目实战(11) 基于OnActionExecuting全局过滤器,页面操作权限过滤控制到按钮级
-
ASP.NET Core配置教程之读取配置信息
-
ASP.NET Core配置教程之读取配置信息
-
.Net Core库类项目跨项目读取配置文件的方法