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();