在ASP.NET Core 6 (.NET 6)中,可以使用Json格式的appsettings.json配置文件来配置应用程序,用于存储应用程序的配置信息,方便我们灵活的配置应用程序。本文主要介绍Program.cs中,使用读取appsettings.json配置文件的方法,以及相关的示例代码。

1、通过配置实体类的方式

1)配置实体类

public class Settings
{
    public string From { get; set; }
    public string SmtpServer { get; set; }
    public int Port { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

2)appsettings.json配置文件内容

"settings": {
    "From": "url@gmail.com",
    "SmtpServer": "smtp.gmail.com",
    "Port": 465,
    "Username": "url@gmail.com",
    "Password": "123456"
  }

3)实现代码

using Microsoft.OpenApi.Models;
using NLog.Web;

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Logging.ClearProviders();
builder.Host.UseNLog();
//获取 appsettings.json 中配置
var settings = builder.Configuration.GetSection("Settings").Get<Settings>();
var smtpServer = settings.SmtpServer;
builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();
ServiceLocator.Instance = app.Services;
//app.UseAuthentication();
//app.UseAuthorization();
app.UseDefaultFiles();
app.UseStaticFiles();
app.MapControllers();
app.Run();

2、通过Configuration属性来获取

1)appsettings.json配置内容

"settings": {
    "From": "url@gmail.com",
    "SmtpServer": "smtp.gmail.com",
    "Port": 465,
    "Username": "url@gmail.com",
    "Password": "123456"
}

2)实现代码

using Microsoft.OpenApi.Models;
using NLog.Web;

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Logging.ClearProviders();
builder.Host.UseNLog();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();
ServiceLocator.Instance = app.Services;
//获取 appsettings.json 中配置
var config = app.Configuration;
var smtpServer = config["settings:SmtpServer"];
//app.UseAuthentication();
//app.UseAuthorization();
app.UseDefaultFiles();
app.UseStaticFiles();
app.MapControllers();


推荐文档