asp.net core 读取appsettings.json

第一次接触asp.net core 所以就想写个程序,那么第一步就是要读取数据库的连接地址,以前都是利用ConfigurationManager.AppSettings["url"];  直接读取,而现在变成json文件了,怎么读取?上网搜了一些资料,有很多关于读取的,但是我的好像有一些不太一样,总之记录一下吧。

appsettings.json 文件

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AppSettings": {
"ConnectionString": "PORT=5432;DATABASE=Demo;HOST=localhost;PASSWORD=root;USER ID=postgres"
},
"AllowedHosts": "*"
}

读取appsettings.json我感觉有两种方式:先说第一种吧

新建个类

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System.IO;

namespace WebApplication2.Data
{
public class ConfigManager
{
public static IConfiguration Configuration { get; set; }

static ConfigManager()
{
//ReloadOnChange = true 当appsettings.json被修改时重新加载

#region 方式1(ok)

Configuration = new ConfigurationBuilder()
.Add(new JsonConfigurationSource
{
Path = "appsettings.json",
ReloadOnChange = true
}).Build();

#endregion

#region 方式2(ok)

//Configuration = new ConfigurationBuilder()
// .SetBasePath(Directory.GetCurrentDirectory())
// .AddJsonFile("appsettings.json").Build();

#endregion
}
}
}

然后在   Controller 里面通过json中的路径直接就可以读取  string appId = ConfigManager.Configuration["AppSettings:ConnectionString"];

第二种方式:感觉有点麻烦

新建一个module

public class AppSettings
{
public string ConnectionString { get; set; }

}

然后在Startup类中的Startup函数中增加 如下所示,红色为新加的

public Startup(IConfiguration configuration)
{
Configuration = new ConfigurationBuilder().
Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true }).Build();
//Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddControllersWithViews();
}

然后在Controller类中这么写,红色的为后加的

private readonly ILogger<ContentController> _logger;
public AppSettings appsettings;
public ContentController(ILogger<ContentController> logger, IOptions<AppSettings> setting)
{
_logger = logger;
appsettings = setting.Value;
}
public IActionResult Index()
{
 string connectionstring = appsettings.ConnectionString;//这样就可以获取了
return View();
}

 项目路径地址 https://github.com/liulangfashi/-appsettings.json

 

不过后来发现一种简单的方式:绿色是asp.netcore跨域的

 

 // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var conStr=  Configuration.GetSection("ConStr");//这是根目录中的
            var ss = Configuration.GetSection("Logging:AppSettings:ConnectionString");//多级可以用这种方式
            SqlHelper.Constr=conStr.Value;
            services.AddControllers();
            services.AddCors(o => o.AddPolicy("any", p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));/**
            这是允许跨域的和Configure方法中的  app.UseCors();是配套使用的,如果允许某些特定的域名来跨域访问,可以
            将AllowAnyOrigin 改为WithOrigins(里面可以是数组),但是该方法和AllowAnyOrigin只能二者存一*/
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseCors();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

posted on 2020-03-14 19:28  流浪法师1  阅读(410)  评论(0编辑  收藏  举报