.Net 6 Web项目Program.cs读取appsettings.json设置参数

 

新建了个.NET 6的Web项目只有Program.cs文件,需要在Program.cs读取appsettings.json里面的配置。

appsettings.json内容如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "default": "Data Source=ip;port=3306; database=db;user id=usr; password=pwd;Convert Zero Datetime=True ; Allow Zero Datetime=True" 

  },
  "JWT": {
    "Key": "zVHFozvvhqgG4gu9Twug6gPcfd9UQrF1"
  } 
}

Program.cs代码如下:

var builder = WebApplication.CreateBuilder(args);

var key = builder.Configuration.GetValue<string>("JWT:Key"); //读取json文件参数

// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
  
var app = builder.Build();
 
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

 
app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

发表回复

您的电子邮箱地址不会被公开。