今天有朋友咨询这个问题,相信一些朋友也会遇到于是在这里写出来给大家提供一些参考
第一种方法:
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;}